0

我使用 Rhino Mocks 编写了以下测试用例来说明我的问题:

[TestClass]
public class Tester
{
    public class TestList<T> : List<T>
    {
        public override bool Equals(object obj)
        {
            // obj is an empty list here??
            return base.Equals(obj);
        }
    }

    public interface IStubbedInterface
    {
        void DoSomethingWithList(TestList<int> list);
    }

    public class ClassToTest
    {
        public IStubbedInterface TheStub { get; set; }

        public void Run()
        {
            var list = new TestList<int> { 1, 2 };
            TheStub.DoSomethingWithList(list);
            list.Clear();
        }
    }

    public bool Match(TestList<int> arg)
    {
        // Here arg is an empty list??
        return arg == new TestList<int> { 1, 2 };
    }

    [TestMethod]
    public void Test()
    {
        var classToTest = new ClassToTest();
        classToTest.TheStub = MockRepository.GenerateMock<IStubbedInterface>();
        classToTest.Run();
        classToTest.TheStub.AssertWasCalled(
            x => x.DoSomethingWithList(new TestList<int>() { 1, 2 }));
            //x => x.DoSomethingWithList(Arg<TestList<int>>.Matches(arg => Match(arg))));
    }
}

无论我是直接比较列表还是使用 Arg<>.Matches(..) 语法,测试用例都会在 AssertWasCalled() 行上失败。我还尝试使用 MockRepository.GenerateStub<>(..) 而不是 GenerateMock<>(..),这也失败了。由于 list.Clear(); 它失败了 调用 DoSomethingWithList() 之后的行,这导致在 AssertWasCalled() 时列表也是空的。这是 RhinoMocks 的错误吗?我会假设 RhinoMocks 会在调用断言函数时以某种方式记录参数的快照,但看起来 RhinoMocks 一直在使用同一个对象?

在我遇到这个问题的真实案例中,我正在测试的函数的参数被包装在 using() 语句中,这导致 AssertWasCalled 无法测试传递的参数的相同效果。

4

1 回答 1

0

看起来使用 Expect()/VerifyAllExpectations() 模式更适合这个测试场景。将测试用例更改为以下代码将通过。

这是相当不幸的,因为我更喜欢使用 AssertWasCalled(),但是就目前而言,它相当不可靠。

[TestMethod]
public void Test()
{
    var classToTest = new ClassToTest();
    classToTest.TheStub = MockRepository.GenerateMock<IStubbedInterface>();
    classToTest.TheStub.Expect(
        x => x.DoSomethingWithList(new TestList<int>() { 1, 2 }));
    classToTest.Run();
    classToTest.TheStub.VerifyAllExpectations();
}
于 2019-12-20T12:50:30.303 回答