Roy Osherove

View Original

Test Coverage and testing angles

How do you know if you have good coverage on your new code?

Try and remove a line or a constraint check. If all tests still pass – you don't have enough code coverage and you probably need to add another unit test.

The best way to make sure you are adding the correct test is to not let yourself uncomment that line or check until you can produce a test that will fail until you uncomment it. It may be hard but if you can’t think of a way this would fail, you probably don’t have a good excuse for writing that line of code, do you?

 

Why is this a problem? Because you never know when the next developer will show up and try to play with your code, maybe try to optimize it, or wrongly delete some precious line of your code.  If you don’t have a test that will fail, they will never know they made a mistake.

 

You might also want to try and replace various usage of parameters that are passed in to your method with consts. For example given this method,

 

Public int Sum(int x, int y, bool allowNegatives)
{
   If(!allowNegatives)
{
        If(x<0||y<0)
        Throw new Exception();
}
   Return x+y;
}

 

here are some variations of testing for test coverage:

   

If(!true)
{
        If(x<0||y<0)
        Throw new Exception();
}
 
Or
 
   If(!allowNegatives)
{
        If(false||y<0)
        Throw new Exception();
}
 
Or
 
If(!allowNegatives)
{
        If(x<0||false)
        Throw new Exception();
}

If all the tests still pass, you’re missing a test.

 

Another red flag: If you have only one test that checks for various equality to values.

Seeing this:

Assert.AreEqual(3,retval);

Happen only once in relation to some method usually means you can safely return 3 as a value and all the tests for this method will still pass.