How to mock the HttpSessionStateBase with vb.NET

91 views
Skip to first unread message

laomao

unread,
Aug 21, 2018, 9:51:44 AM8/21/18
to NSubstitute
Here is my unit test code in vb.NET
<Fact>
Public Sub Session_Should_Have_Item()
Dim httpContext = Substitute.[For](Of HttpContextBase)()
Dim expected = 1008
httpContext.Session("RoleId").Returns(expected)
Dim actual = httpContext.Session("RoleId")
actual.Should().Be(expected)
End Sub

the run time error "System.NullReferenceException' occurred in Microsoft.VisualBasic.dll but was not handled in user code Additional information: Object variable or With block variable not set" is thrown at this line:

httpContext.Session("RoleId").Returns(expected)

It seems to me that NSubstitute doesn't support vb.NET very well -- it has trouble to parse the parenthesis. Can anybody confirm that is the issue?

David Tchepak

unread,
Aug 21, 2018, 8:49:36 PM8/21/18
to nsubs...@googlegroups.com
Hi,
I am not proficient with VB, but I believe this is due to late binding
as described here: https://stackoverflow.com/a/48936317/906.

The solution is to explicitly call the `Returns` extension method
whenever you have a reference to type `Object` so that late-binding is
not used:

<TestMethod()> Public Sub Session_Should_Have_Item()
Dim httpContext = Substitute.[For](Of HttpContextBase)()
Dim expected = 1008
SubstituteExtensions.Returns(httpContext.Session("RoleId"), expected)
Dim actual = httpContext.Session("RoleId")
Assert.AreEqual(expected, actual)
End Sub

This can be made a little simpler with aliases: `Imports NSub =
NSubstitute.SubstituteExtensions`, then `NSub.Returns(...)`. As far as
I can tell this should only be required when you have a reference to a
`System.Object`.

NSubstitute's syntax was tailored for C# and can sometimes be a bit
clunky in VB, but it doesn't specifically parse the VB or C# code (it
just works from the compiled .NET DLL) so it should not be a problem
from that perspective.

Regards,
David
> --
> You received this message because you are subscribed to the Google Groups "NSubstitute" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to nsubstitute...@googlegroups.com.
> To post to this group, send email to nsubs...@googlegroups.com.
> Visit this group at https://groups.google.com/group/nsubstitute.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages