One assert per test, really
- 2 min
Recently I was debugging my code and I could not see why my test was failing. It took me about 20 minutes to see that I violated one rule I try to follow. One assert per test. After tweeting it I got some reaction ranging from 'this is a very silly guideline' to 'Tests should test one thing. Often one assertion, but not always.'. I, of course, tend to agree the latter one. So what's in for you when you use one assert per test? What are the problems?
One the plus side:
- If a tests fails, you know what is wrong.
- You know how to name your test method, since you are just testing one thing.
- It plays very nicely along with Test Driven Development, test and implement one feature at a time and make it work.
- If you change one thing in your code, at best only one unit test will fail (ok, this one is hard but possible).
- With multiple asserts you fix one assert which is broken and only then you see that the next one is broken too.
- You need to think more about the test setup, it should be possible to really just test one thing and mock the rest. Think, design for testability.
- More (test) code.
- It looks like it is easier to have multiple asserts.
@Test
public void testAddSubscriber() {
TestEventSubscriber eventSubscriber = new TestEventSubscriber();
eventPublisher.registerSubscriber(eventSubscriber);
assertThat(eventPublisher.getEventSubscribers()).
containsOnly(eventSubscriber);
}
If you don’t know it, try it. I do like it.
Which thoughts do you have ?