针对存根方法的多个Expect的RhinoMocks VerifyAllExpectations失败

时间:2017-07-04 13:10:33

标签: c# unit-testing rhino-mocks

亲爱的RhinoMocks用户。我是RhinoMocks的新手,并且在我的脑袋周围有问题。我需要在一个类中测试两个方法,在它们中多次调用另一个方法。我已经分别测试了多次调用的那个,设置有些复杂,所以测试另一种方法的想法是将已经测试过的方法存根。这是一个最小的例子:

-------------------------------------
test string: 1
regex: \d
-------------------------------------
test string: 1
regex: \w
SVLIB Test passed!
UVM Test passed!

即。 public class TestedClass { public virtual void DoSthOnce(List<int> listParam) { foreach (var param in listParam) DoSthMultipleTimes(param); } public virtual void DoSthMultipleTimes(int intParam) { Console.WriteLine("param: " + intParam); } } 已经过测试。以下测试代码可用,并验证为DoSthMultipleTimes()的参数提供的列表的每个元素都调用了DoSthMultipletimes() - 方法。

DoSthOnce()

输出符合预期:

    var paramList = Enumerable.Range(1, 10).ToList();
    var mock = MockRepository.GeneratePartialMock<TestedClass>();
    mock.Stub(m => m.DoSthMultipleTimes(Arg<int>.Is.Anything))
        .WhenCalled(mi =>
        {
            // Only for debug; this method is empty in the actual test code.
            Console.WriteLine("Stub called with " + mi.Arguments[0]);
        });

     mock.DoSthOnce(paramList);

     // This will not throw an exception
     foreach (var param in paramList)
         mock.AssertWasCalled(m => m.DoSthMultipleTimes(param));

然而,以下内容未能抛出异常,尽管它应该与上述相同,至少从我的理解来看:

    Stub called with 1
    Stub called with 2
    Stub called with 3
    Stub called with 4
    Stub called with 5
    Stub called with 6
    Stub called with 7
    Stub called with 8
    Stub called with 9
    Stub called with 10

控制台输出相同,但 var paramList = Enumerable.Range(1, 10).ToList(); var mock = MockRepository.GeneratePartialMock<TestedClass>(); mock.Stub(/*same as above*/).WhenCalled(/*same as above*/); foreach (var param in paramList) mock.Expect(m => m.DoSthMultipleTimes(param)); mock.DoSthOnce(paramList); mock.VerifyAllExpectations(); 抛出了ExpectationViolationException。其他信息是:

VerifyAllExpectations()

参数是正确的,但究竟是什么问题呢?

1 个答案:

答案 0 :(得分:0)

我因为你的存根本身而猜测。

这段代码会记录您想要的各种期望:

foreach (var param in paramList)
    mock.Expect(m => m.DoSthMultipleTimes(param));

这将设置正在调用DoSthMultipleTimes(1),DoSthMultipleTimes(2)等的期望。

但是你的Mock.Stub代码会覆盖/存根实现本身。这导致Rhino将执行此覆盖/方法(而不是调用原始类的原始DoSthMultipleTimes方法)。因此,当调用VerifyAllExpectation时,没有调用原始类中的方法。

您可以通过删除以下内容来验证上述内容:

mock.Stub(m => m.DoSthMultipleTimes(Arg<int>.Is.Anything))
    .WhenCalled(mi =>
    {
        // Only for debug; this method is empty in the actual test code.
        Console.WriteLine("Stub called with " + mi.Arguments[0]);
    });

由于您使用的是PartialMock,如果您没有实现存根,它将调用原始方法。据说,现在它将成功通过所有期望。

(注意:当使用PartialMock时要小心,因为如果没有被存根(例如:数据库调用等),它将运行原始方法。)

相关问题