Multiple Asserts in a Single Unit Test

There is a debate going on about having one assertion per test.

James Avery argues that what he’d really like to see in a unit test framework is the ability to run (and fail) multiple asserts within the same test and Roy Osherov still argues that there is value in having one assertion only.

I am less inclined to force a one assertion per test as it might add unneeded burden on the developer, who has to set up the same test scenario for each test. This will require Refactoring the test and Extracting a setup method. On the other hand I would not want the tests to continue to run once the first test has failed, as Roy correctly pointed out, we are in a dirty state.

As we know, there is no Silver Bullet we are going to have to rely on the developers to take the call and decide what is best for them.

I am in favor developers being guided by:
The Test Should Test Only ONE scenario

This does not mean one assert! it means one scenario.

If we need to assert several items to verify that the scenario works, we should do it in the same test (This is how all mocking frameworks work anyway).

In the examples that James brings, each test verifies one scenario but requires several asserts. I believe that this is good practice.


Add Comment

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