Using Moq to check the values of an object passed to a method

In order to test individual properties of an object passed to a method using Moq I have been making use of my Assert.IsFieldEqual method. See here for details.

Because I can’t call the Assert.IsFieldEqual inside a lambda, like so …


    _mockBus
        .Verify(x => x.Send(It.Is<MyMessage>(m => Assert.IsFieldEqual(m, propertyName, expectedValue))), Times.Once());

Obviously, since makes no sense as the Assert.IsFieldEqual is a void method. So, I’ve made use of Moq’s callback facility.


    MyMessage sentMessage = null;

    _mockBus
        .Setup(x => x.Send(It.IsAny<MyMessage>()))
        .Callback<object>((m) => sentMessage = (MyMessage) (((object[]) m)[0]));

    Assert.IsFieldEqual(sentMessage, propertyName, expectedValue);

This allows me to have a TestCase for each property in the message, so I have one test method for all the properties.

Advertisements

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