Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSubstitute: Arg.Do does not fulfill the list of called parameters

Tags:

nsubstitute

For the code bellow I get this assert failure and do not know why:

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);
    }
}
like image 611
Petr Felzmann Avatar asked Dec 25 '22 19:12

Petr Felzmann


1 Answers

The code is setting up an action to perform (Arg.Do) after the calls have already been made. I think this is what you are after:

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);
like image 69
David Tchepak Avatar answered May 08 '23 11:05

David Tchepak