Top 12 Selected Unit Testing Best Practices


Google+ Facebook Twitter LinkedIn Dzone Reddit Digg Blogger Hacker News Addthis

By Markus Sprunck; Revision: 1.0; Status: final; Last Content Change: Oct 21, 2013; 

The following list of twelve selected best practices are the most important things you should know about unit testing.

Always Write Isolated Test Cases
- The order of execution has to be independent between test cases

Test One Thing Only in One Test Case
- Each test should focus on one aspect of an isolated method and/or class

Use a Single Assert Method per Test Case
- Don't test too many different things at once! If you use just one Assert it's easier

Use a Naming Convention for Test Cases
- A convention like: <Method-Name Under Test>_<Scenario>_<Expected-Outcome> 

Use the AAA Pattern
- Use separated blocks ("ARRANGE", "ACT" and "ASSERT") help to improve maintainability 
- Use comments to mark the blocks

Avoid the Expected Exception Tests
- Maybe @Test(expected = ArithmeticException.class) doesn't test what it claims to test 

Structure All Test Cases
- Like Short-/Long-Running, Integration-/Unit-tests, but don't use test suits to control order of execution 

Use Descriptive Messages in Assert Methods
- Describe the WHY and not the WHAT, not like Assert.assertEquals( a, b, "must be equal") 

Measure Code Coverage to Find Missing Test Cases
- Best indicator what is not tested, but don't be to sure that the code works

Don't Forget to Refactor the Test Code
- Also maintain your test code 

Limit Use of Mocks
- In some cases absolutely necessary, but with better design stubs should be enough 

Use Parameterized Tests
- They can help avoid duplication and the best is the business gives you the data

Remarks

All the best practices you may read here have been invented by someone else. I just collected all the good ideas (from books, trainings, blogs) and ranked them according my personal experiences. Please, do not hesitate to contact me if you have any ideas for improvement.

Change History

 Revision  Date  Author  Description
 1.0  Oct 21, 2013  Markus Sprunck  first version

Google+ Comments

You may press the +1 button to share and/or comment