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

Jan picture Jan · Jul 17, 2010 · Viewed 86.6k times · Source

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?

Answer

Gamlor picture Gamlor · Jul 20, 2010

You can use the Mock.Callback-method:

var mock = new Mock<Handler>();
SomeResponse result = null;
mock.Setup(h => h.AnsyncHandle(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.AnsyncHandle(It.Is<SomeResponse>(response => response != null)));