C# – Moq: How to get to a parameter passed to a method of a mocked service

cmoq

Imagine this class

public class Foo {

    private Handler _h;

    public Foo(Handler h)
    {
        _h = h;
    }

    public void Bar(int i)
    {
        _h.AsyncHandle(CalcOn(i));
    }

    private SomeResponse CalcOn(int i)
    {
        ...;
    }
}

Mo(q)cking Handler in a test of Foo, how would I be able to check what Bar() has passed to _h.AsyncHandle?

Best Answer

You can use the Mock.Callback-method:

var mock = new Mock<Handler>();
SomeResponse result = null;
mock.Setup(h => h.AsyncHandle(It.IsAny<SomeResponse>()))
    .Callback<SomeResponse>(r => result = r);

// do your test
new Foo(mock.Object).Bar(22);
Assert.NotNull(result);

If you only want to check something simple on the passed in argument, you also can do it directly:

mock.Setup(h => h.AsyncHandle(It.Is<SomeResponse>(response => response != null)));