【问题标题】:How to mock the HttpSessionStateBase with NSubstitute如何使用 NSubstitute 模拟 HttpSessionStateBase
【发布时间】:2018-08-17 21:32:05
【问题描述】:

在 Moq 中,我可以像这样设置会话变量(vb.NET 代码):

Dim httpContext As Mock(Of HttpContextBase) = New Mock(Of HttpContextBase)()
Dim httpRequest As Mock(Of HttpRequestBase) = New Mock(Of HttpRequestBase)()
Dim httpResponse As Mock(Of HttpResponseBase) = New Mock(Of HttpResponseBase)()
Dim httpSession As Mock(Of HttpSessionStateBase) = New Mock(Of HttpSessionStateBase)()
**httpSession.Setup(Function(s) s("RoleId")).Returns(1008)**
...

我如何使用 NSubstitute 来做到这一点?

我已经尝试了这些但没有工作:

HttpSession.Item("RoleId").Returns(1008) 'but got the error NullReferenceExpection.

httpContext.Session("RoleId").Returns(1008) 'but got the same error

更新: 尝试了 Nkosi 的 C# 示例,它起作用了。但是,当像这样将其转换为 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

正如我之前提到的那样,运行时错误被抛出:

enter code here`httpContext.Session("RoleId").Returns(expected)

在我看来,NSubstitute 对 vb.net 的支持不是很好——解析括号有困难。谁能确认这是问题所在?

【问题讨论】:

  • 错误消息是:Microsoft.VisualBasic.dll 中出现“System.NullReferenceException”类型的异常,但未在用户代码中处理附加信息:未设置对象变量或块变量。跨度>

标签: vb.net unit-testing session moq nsubstitute


【解决方案1】:

试试下面的

Dim httpContext As HttpContextBase = Substitute.For(Of HttpContextBase)()
Dim httpSession As HttpSessionStateBase = Substitute.For(Of HttpSessionStateBase)()

httpSession("RoleId").Returns(1008)

httpContext.Session.Returns(httpSession)

其中引用了文档中的示例。

虽然Auto and recursive mocks 在这种情况下应该可以工作,但您可以采用上面演示的详细方法

尽管在 c# 中,当使用带有递归模拟的 NSubstitute 时,以下操作确实有效

[Fact]
public void Session_Should_Have_Item() {
    //Arrange
    var httpContext = Substitute.For<HttpContextBase>();
    var expected = 1008;
    httpContext.Session["RoleId"].Returns(expected);

    //Act
    var actual = httpContext.Session["RoleId"];

    //Assert
    actual.Should().Be(expected);
}

【讨论】:

  • 我尝试了 "httpSession("RoleId").Returns(1008)" 语句,但得到了我之前提到的相同错误。将研究您提供的链接并尝试那里的示例。
  • 我已经尝试过您的 C# 代码并且它正在工作。但是,当我将它转换成这样的 vb.net 代码时: Public Sub Session_Should_Have_Item() Dim httpContext = Substitute.[For](Of HttpContextBase)() Dim expected = 1008 httpContext.Session("RoleId").Returns(预期) Dim actual = httpContext.Session("RoleId") actual.Should().Be(expected) End Sub 错误转到以下行:httpContext.Session("RoleId").Returns(expected)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 2016-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多