Asserting multiple properties of argument with FakeItEasy

More often than not, I want to assert that my dependency has been called with a parameter that matches more than one condition.

Let’s say we have a method that calls ICustomerService.Add method.
We want to assert the Add method was called with a Customer that matches a few conditions.

The way we’d typically achieve this is by doing something like this:

var fake = A.Fake<ICustomerService>();

A.CallTo(() => fake.AddCustomer(
    A<Customer>.That.Matches(c =>
        c.Property == "123" &&
        c.OtherProperty == "345" &&
        c.AnotherProperty == "456" &&
        c.YetAnotherProperty == "567"

This will work. And it will indeed assert that the AddCustomer method was called with a Customer object, with those properties set to the corresponding values.

The problem lies if one of those properties doesn’t match.
We get a failed test. But no idication of which property it’s failed on.

What I like to do instead, is follow this pattern:

Customer addedCustomer;

A.CallTo(() => a.Add(A<Customer>._))
    .Invokes(c => addedCustomer = c.GetArgument<Customer>(0));

//Individual Asserts on addedCustomer
Assert.AreEqual("123", addedCustomer.Property);
Assert.AreEqual("345", addedCustomer.OtherProperty);
Assert.AreEqual("456", addedCustomer.AnotherProperty);
Assert.AreEqual("567", addedCustomer.YetAnotherProperty);

So, here, we’re basically saying when Add is called, with any Customer object, Invoke the anonymous function, that takes the Customer argument, and stores it in addedCustomer.

We can then individually assert on each property.

I created an issue on GitHub which addresses this, with a view to finding a more ‘inline’ solution

Leave a Reply

Your email address will not be published. Required fields are marked *