NSubstitute:Arg.Do不满足被调用参数列表

时间:2013-10-09 14:40:50

标签: nsubstitute

对于下面的代码,我认为这个断言失败了,不知道为什么:

Assert.AreEqual failed. Expected:<2>. Actual:<0>.

public interface IA
{
    void MethodA(B b);
}

public class A : IA
{
    public void MethodA(B b) {/*no matter*/}
}

public class B
{
    public string PropertyB { get; set; }
}

public class MyLogic
{
    private IA _a;
    public MyLogic(IA a)
    {
        _a = a;
    }
    public void DoLogic()
    {
        _a.MethodA(new B { PropertyB = "first" });
        _a.MethodA(new B { PropertyB = "second" });
    }
}

[TestClass]
public class MyLogicTests
{
    [TestMethod]
    public void CallTwiceAndCheckTheParams()
    {
        List<B> args = new List<B>();
        IA a = Substitute.For<IA>();

        new MyLogic(a).DoLogic();

        a.Received(2).MethodA(Arg.Do<B>(x => args.Add(x)));
        Assert.AreEqual(2, args.Count);
    }
}

1 个答案:

答案 0 :(得分:6)

代码正在设置要在执行调用后执行的操作(Arg.Do)。我想这就是你追求的目标:

List<B> args = new List<B>();
IA a = Substitute.For<IA>();
a.MethodA(Arg.Do<B>(x => args.Add(x))); // do this whenever MethodA is called

new MyLogic(a).DoLogic();

a.Received(2).MethodA(Arg.Any<B>());
Assert.AreEqual(2, args.Count);