1

我需要测试执行函数的逻辑,之后它会更改参数的属性,然后使用更新的参数执行相同的函数。

为了帮助说明这一点,这里有一些示例代码:

接口: public interface IWorker { MyObjectB DoWork(MyObject myObject); }

我的对象B: public class MyObjectB { public string Message { get; set; } }

执行:

public MyObjectB DoWork(IWorker worker, MyObject myObject)
{
    worker.DoWork(myObject);
    myObject.Name = "PersonB";
    worker.DoWork(myObject);
    return new MyObjectB() { Message = "Done" };
}

测试:

    public void RhinoMocksSampleTest()
    {
     var workerStub = MockRepository.GenerateStub<IWorker>();
     workerStub.Stub(n => n.DoWork(Arg<MyObject>.Is.Anything));

     var myObj = new MyObject { Id = 1, Name = "PersonA" };

     var p = new Program();
     p.DoWork(workerStub, myObj);

     workerStub.AssertWasCalled(d => d.DoWork(Arg<MyObject>.Matches(r => r.Name == "PersonA")));

     workerStub.AssertWasCalled(d => d.DoWork(Arg<MyObject>.Matches(r => r.Name == "PersonB")));
    }

第一个 AssertWasCalled 失败,因为值为“PersonB”。是否有一个函数/调用可以用来测试第一次调用的对象状态?

4

2 回答 2

1

以下是我将如何做你想做的事情:

public void RhinoMocksSampleTest()
{
    var workerMock = MockRepository.GenerateMock<IWorker>();
    workerMock.Expect(d => d.DoWork(Arg<MyObject>.Matches(r => r.Name == "PersonA")));
    workerMock.Expect(d => d.DoWork(Arg<MyObject>.Matches(r => r.Name == "PersonB")));

    var myObj = new MyObject { Id = 1, Name = "PersonA" };
    var p = new Program();
    p.DoWork(workerMock , myObj);

    workerMock.VerifyAllExpectations();
}
于 2012-12-17T17:52:51.700 回答
0

除了 aprescott 提供的很好的答案之外,我还可以展示另一种在某些情况下可能有用的方法:

这个想法是将您感兴趣的值手动存储到某个集合中。然后您将能够断言该集合包含所需的序列。

    public void MyTest()
    {
        // that is list which will contain passed names
        var actualNames = new List<string>();

        // stub only saves passed Name property into list
        var workerStub = MockRepository.GenerateStub<IWorker>();
        workerStub
            .Stub(w => w.DoWork(Arg<MyObject>.Is.Anything))
            .Do((Action<MyObject>)(mo => actualNames.Add(mo.Name)));

        var myObject = new MyObject { Name = "PersonA" };
        var target = new MyWorker();

        target.DoWork(workerStub, myObject);

        // here we do assert that names list contains what is required
        Assert.That(actualNames, Is.EqualTo(new[] { "PersonA", "PersonB" }));
    }

PS。是的,它适用于您需要检查呼叫顺序是否正确的情况:)

于 2012-12-17T20:10:02.523 回答