Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tricks for writing better unit tests [closed]

What are some of the tricks or tools or policies (besides having a unit testing standard) that you guys are using to write better unit tests? By better I mean 'covers as much of your code in as few tests as possible'. I'm talking about stuff that you have used and saw your unit tests improve by leaps and bounds.

As an example I was trying out Pex the other day and I thought it was really really good. There were tests I was missing out and Pex easily showed me where. Unfortunately it has a rather restrictive license.

So what are some of the other great stuff you guys are using/doing?

EDIT: Lots of good answers. I'll be marking as correct the answer that I'm currently not practicing but will definitely try and that hopefully gives the best gains. Thanks to all.

like image 912
Fung Avatar asked Mar 31 '09 02:03

Fung


1 Answers

  1. Write many tests per method.
  2. Test the smallest thing possible. Then test the next smallest thing.
  3. Test all reasonable input and output ranges. IOW: If your method returns boolean, make sure to test the false and true returns. For int? -1,0,1,n,n+1 (proof by mathematical induction). Don't forget to check for all Exceptions (assuming Java). 4a. Write an abstract interface first. 4b. Write your tests second. 4c. Write your implementation last.
  4. Use Dependency Injection. (for Java: Guice - supposedly better, Spring - probably good enough)
  5. Mock your "Unit's" collaborators with a good toolkit like mockito (assuming Java, again).
  6. Google much.
  7. Keep banging away at it. (It took me 2 years - without much help but for google - to start "getting it".)
  8. Read a good book about the topic.
  9. Rinse, repeat...
like image 196
jasonnerothin Avatar answered Dec 13 '22 15:12

jasonnerothin