11 Tips for Successful Unit Testing Posted on June 25, 2015 by Alain Unit testing makes or breaks a software development project. In small scale projects with a short life expectancy, this may not be integral but this is not the case for long-term projects. Maintainability of the source code matters, and testable code equals maintainable code. Unit testing your code will increase the lifespan of your application by several years, and significantly reduces the cost of change. 1. Aim for 85% coverage but never neglect to test all your states. 2. Use code conventions of your test methods. We use Name_Scenario_ExpectedResult(), or Name_Scenario_ExpectedExceptionType(). Using these conventions, you can omit documentation and read from the name what the test is supposed to do, for instance Constructor_NullInput_ThrowsArgumentNullException(). 3. Isolate your class completely from external classes through stubbing and proper use of abstraction. When your test fails this may only be because of code in the class itself. 4. For better maintainability standardize variable names for your variables in the test methods: We use target, expected, actual 5. Treat test code like you would treat production code. This means staying DRY and refactoring the code where necessary. 6. Execute your tests before checking in your code. Do not accept any failing tests. If the project is small enough, you can use the gated check-in feature in TFS (or Visual Studio Online) to ensure this. 7. With experienced developers practicing TDD can even contribute to a better technical design. 8. Test only your public methods. Your private methods should automatically be covered by calling your public methods. 9. Place your tests in a location that can be easily tracked or derived from the name of the class under test. We use the following conventions: If we are testing Project.Module.Class, our test class can be found in Project.Module.Tests.ClassTest. 10. A good unit test is fast, repeatable and has a single assert. Another assert is another test. 11. Unit testing is necessary. It takes longer and it gives you as much test code as production code but in the long run, it keeps cost of change low and it gives developers confidence that his/her change does not affect the legacy code. It also increases the lifespan of your application by several years.