Should tests perform a single assertion, or are multiple related assertions acceptable

by Unflux   Last Updated July 11, 2019 15:05 PM

Assume a client is making a request to an API endpoint that returns a JSON response where the structure and data change depending on whether the request was successful or not. Possible responses may look as follows:

Scenario with a success response

{
  "status": XXX,
  "data": [{
    ...
  }]
}

Scenario with a failure response

{
  "status": XXX,
  "errors": [{
    ...
  }]
}

Example of test scenarios for the above would be:

  • Assert the expected status code
  • Assert the expected JSON structure
  • Assert the expected JSON data

When performing tests where you have more than one assertion you can perform, is it recommended to provide a single test for each assertion, or group the assertions into a single test?



Answers 1


Each unit test should assert a single requirement.

Now, you may not always have formal requirements for every method. Methods are written in pursuit of fulfilling such formal requirements. But given that a method should do only one thing, should have a single purpose, you should already have a fair idea of what to expect from the method in terms of behavior.

Consider your first example. You could always just assert against the entire output (pseudocode follows):

Assert.AreEqual(result, @"{
  'status': XXX,
  'data': [{
    ...
  }]
}");

But such tests are brittle, and when they break, there is no indication of what went wrong or what requirement is not being met. You have to look through the output and see where the actual problem is, and then analyze the problem to determine what requirement is not being met.

Asserting on a single requirement means you can give your unit test a meaningful name that states specifically what requirement is being tested. There are a number of ways to do that.

Given_UserIsAuthenticated_When_InvalidAccountNumberIsUsedToWithdrawMoney_Then_TransactionWillFail()  

When the test fails, it will show up in your test runner with the meaningful name and you will know precisely which requirement is not being met.

Robert Harvey
Robert Harvey
July 11, 2019 14:51 PM

Related Questions



How to manage non-unit tests in a project?

Updated April 26, 2017 14:05 PM


Unit testing and other forms of testing

Updated February 28, 2018 05:05 AM