views:

156

answers:

6

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 .

+5  A: 

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

Christian
often unit-tests too are broken: test logic is wrong and you get a false sense of confidence with your code
dfa
+1  A: 
  • Break the code in test regularly to see the effectiveness of the unit tests
jhwist
+4  A: 

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.
Mark Seemann
+1 for xUnit Test Patterns: a great book
dfa
+1 for "Keep it fast".
Aaron Digulla
+2  A: 

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.

philippe
A: 

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

Aaron Digulla
+1  A: 

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).

starblue