Tutorial :Guidelines for better unit tests [closed]


Jimmy Bogard, wrote an article: Getting value out of your unit tests, where he gives four rules:

  • Test names should describe the what and the why, from the user’s perspective
  • Tests are code too, give them some love
  • Don’t settle on one fixture pattern/organizational style
  • One Setup, Execute and Verify per Test

In your opinion these guidelines are complete? What are your guidelines for unit tests? Please avoid specific language idioms, try to keep answers language-agnostic .


There's an entire, 850 page book called xUnit Test Patterns that deal with this topic, so it's not something that can be easily boiled down to a few hard rules (although the rules you mention are good).

A more digestible book that also covers this subject is The Art of Unit Testing.

If I may add the rules I find most important, they would be:

  • Use Test-Driven Development. It's the by far the most effective road towards good unit tests. Trying to retrofit unit tests unto existing code tend to be difficult at best.
  • Keep it simple: Ideally, a unit test should be less than 10 lines of code. If it grows to much more than 20 lines of code, you should seriously consider refactoring either the test code, or the API you are testing.
  • Keep it fast. Unit test suites are meant to be executed very frequently, so aim at keeping the entire suite under 10 s. That can easily mean keeping each test under 10 ms.


Writing unit-tests is simple, it is writing unit-testable code that is difficult.


The Way of Testivus

  • If you write code, write tests.
  • Don’t get stuck on unit testing dogma.
  • Embrace unit testing karma.
  • Think of code and test as one.
  • The test is more important than the unit.
  • The best time to test is when the code is fresh.
  • Tests not run waste away.
  • An imperfect test today is better than a perfect test someday.
  • An ugly test is better than no test.
  • Sometimes, the test justifies the means.
  • Only fools use no tools.
  • Good tests fail.


  • Break the code in test regularly to see the effectiveness of the unit tests


Take a look at the code coverage of your tests, and try to make it reasonably complete (for error cases I'd use some discretion whether to test them or not).


For many more good ideas to write unit tests, search stackoverflow.com.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »