Moq’s Setup, Verify, Verifiable and Callback Methods

(The code here is C#)

When trying to verify parameters passed to a method on a mocked object:

Method 1:

• Use Setup (which has taken the place of Expect)
• Use It.Is(x => x == ExpectedParameter)
• The lambda expression can be as complex as you like, as long as it returns a Boolean
• !! Important !! Mark it verifiable!

Like this:

mock
.Setup(x => x.Method(It.Is(y => y == "expected")))
.Verifiable();

mock.Verify();

Method 2:

Use callback: This allows you to store the parameter in your own variable and then make assertions on its contents.

Like this:

string actual = String.Empty;
mock.Setup(x => x.Method(It.IsAny()))
.Callback((param) => actual = param);

Assert.Equal("expected", actual);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s