Simplify your test assertions

Came across this failing test, immediately felt a bit verbose… with testing in general the simpler and cleaner your tests can stay the better, otherwise test rot starts to creep up, developers procrastinate
about fixing them etc….

The test assertion was:


It Should_be_add_a_message_to_the_contractor_conversation = () =>
{
Assert.That(_contractor.Messages, Has.Some.InstanceOf().And.All.With.Property("Content").EqualTo(messageContent));
};

Changed to:


It Should_be_add_a_message_to_the_contractor_conversation = () =>
{
_contractor.Messages.ShouldContainAny(m => m.Content == messageContent);
};

The extension method:


public static void ShouldContainAny(this IEnumerable list, Func comparer, params T[] items)
{
if (items.Any(comparer))
{
throw new SpecificationException(string.Format(@"Should contain any matching item but contains none"));
}
}

Advertisement

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 )

Connecting to %s