【问题标题】:Why does RhinoMocks behave differently in VB & C#?为什么 RhinoMocks 在 VB 和 C# 中的行为不同?
【发布时间】:2013-07-11 11:18:02
【问题描述】:

我有类似这样的测试代码:

Public Interface IDoSomething
   Function DoSomething(index As Integer) As Integer
End Interface

<Test()>
Public Sub ShouldDoSomething()
   Dim myMock As IDoSomething = MockRepository.GenerateMock(Of IDoSomething)()

   myMock.Stub(Function(d) d.DoSomething(Arg(Of Integer).Is.Anything))
      .WhenCalled(Function(invocation) invocation.ReturnValue = 99)
      .Return(Integer.MinValue)

   Dim result As Integer = myMock.DoSomething(808)

End Sub

此代码的行为与预期不符。正如预期的那样,变量 result 包含 Integer.MinValue 而不是 99。

如果我用 C# 编写等效代码,它会按预期工作:result 包含 99。

有什么想法吗?

C# 等效项:

public interface IDoSomething
{
   int DoSomething(int index)
}

[test()]
public void ShouldDoSomething()
{
   var myMock = MockRepository.GenerateMock<IDoSomething>();

   myMock.Stub(d => d.DoSomething(Arg<int>.Is.Anything))
      .WhenCalled(invocation => invocation.ReturnValue = 99)
      .Return(int.MinValue);

   var result = myMock.DoSomething(808);
}

【问题讨论】:

  • 您也应该提供 C# 代码。您认为等效的可能并非如此,并且可能是答案所在。
  • 咦,为什么要提供两个不同的返回值?你不能放弃WhenCalled() 而只使用Return() 吗?但不知道行为不同的原因。

标签: c# vb.net unit-testing rhino-mocks rhino-mocks-3.5


【解决方案1】:

区别在于Function(invocation) invocation.ReturnValue = 99 是一个内联函数,返回一个Boolean,而invocation =&gt; invocation.ReturnValue = 99 是一个内联函数,返回99 并将invocation.ReturnValue 设置为99

如果您使用的是足够晚的 VB.NET 版本,则可以使用 Sub(invocation) invocation.ReturnValue = 99,除非 WhenCalled 需要返回值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2010-10-03
    • 2010-12-29
    • 2012-04-22
    • 2012-07-09
    • 2016-06-02
    相关资源
    最近更新 更多