Tuesday, January 11, 2011

Unit Tests: What to Test?

Have you read the book Pragmatic Unit Testing in c# with NUnit?
No, read it (it's a must):

 

Well the book has this poster at the back:

Unit-Tests-what-to-test

(click here to get a PDF version directly from their site)


 

Well what I like to test are these things:

1. Right: given good parameters is the function returning good results?

2. Boundary Conditions: given parameters such as null values, empty string, empty list, negative/zero index, out of bound indexes is the method returning the right results (either returns an error, throws an exception or does nothing).

3. Inverse: if you can write some code that returns your parameters back, test that you are getting them back. For example 3++ = 4 , 4-- = 3

4. Cross-Check: if you can write some code that runs the method in a different way, test that for the same input you get the same results. For example: 3++ = 4 , 3+1 = 4

5. Error Condition: test for exceptions – for the right parameters the method throws an exception of the right type. For example when dividing by zero an exception of type DivideByZeroException is thrown.

6. Performance: test for the time/memory/CPU the method took to run



My preferred way of writing Unit tests is:

  1. public class TestedClassTests
  2. {
  3.     public void TestedMethod_WhatIsTested_ExpectedResult(){...}
  4. }

If you tried that and are using Resharper you will get a warning that the naming convention is wrong but there is a solution.

 

Now I usually use a Live Template from Resharper that automatically creates regions with test methods for all the test cases. I have put the template in my Codeplex Project: ResharperTemplates\TestTemplate_ResharperLive.xml



//TODO: Add VS Snippets
Resources:
How to change the ReSharper naming style for test methods

http://stackoverflow.com/questions/463595/poll-c-apps-memory-usage-at-runtime

http://stackoverflow.com/questions/275957/can-a-c-program-measure-its-own-cpu-usage-somehow


Keywords: Unit test, beginner, ExpectException, Exception, Resharper