Writing Better Assertions: Stop Using Assert.True for Expressions

The Problem: Using Assert.True For Expressions

One thing I keep running into in codebases lately (especially those where the team was new to writing automated tests), is assertions using expressions with Assert.True (or equivalent depending on your framework or language). The problem here is consider the following code:

[Fact]
public void AddShouldSumNumbers()
{
var result = CalculatorService.Add(1, 1);
Assert.True(result == 3);
}

At quick glance, you can probably tell that this assertion will fail, because 1+1 is not equal to 3. Let’s take a look at the test output:

Cool, we found out it failed… now what? How do we debug what the problem is? There’s very little useful information here. All we know is that result is not equal to 3, but we have no clue what the value of result even is. We would have to either set a break point to inspect the value or add some sort of logging.

The Solution: Use Assert.Equal

The solution to this is using Assert.Equal (or equivalent) that will automatically log out the actual value for you in the event the test fails. So the test output for this code:

[Fact]
public void AddShouldSumNumbers()
{
var result = CalculatorService.Add(1, 1);
Assert.Equal(3, result);
}

Will yield this result:

Awesome, now we know that result is 2 without having to do any extra work!

Next Blog Post: Use Something Other Than Assert.Equal

There are still improvements we can make to Assert.Equal which is to say, using something else entirely, but that’ll be for the next blog post. 😄