views:

51

answers:

2

I am new to code-coverage, and I am trying to get my unit tests to cover %100 of my code.

My first question is, is this possible/feasible?

My second, more specific question is, I have the following method:

/// <summary>
/// Clears frames, control groups, display groups
/// </summary>
public bool Clear()
{
    try
    {
        this.Frames.Clear();
        this.ControlGroups.Clear();
        this.DisplayGroups.Clear();
        return true;
    }
    catch (Exception ex)
    {
        Milltown.MTCore.mtException mtEx = new Milltown.MTCore.mtException((int)PFExceptions.Exception_Hidden_FuctionLevel, ex,
        PFCommonVariables.ApplicationPlatform, PFCommonVariables.ApplicationDataSource, "PFSystem:Clear");
        return false;
    }

}

My unit test for this method is:

//System Clear Test
Assert.IsTrue(MySystem.Clear());
Assert.AreEqual(0,MySystem.Frames.Count);
Assert.AreEqual(0,MySystem.ControlGroups.Count);
Assert.AreEqual(0, MySystem.DisplayGroups.Count);

Code coverage shows that I am covering the lines inside the try block, but not the catch block. How can I cover the code in catch blocks?

+2  A: 

Improving your coverage is a good goal. Don't get too focused on the 100% number: it can be very misleading. More coverage is better than less, but even at 100%, you could be missing many aspects of your code (see http://nedbatchelder.com/blog/200710/flaws_in_coverage_measurement.html for examples in Python). And the last 5% of coverage may not tell you as much as you would like.

As for your exceptions, you'll need a way to force an exception to be thrown from one of your methods. A common way to do this is to mock out the implementation so you can decide what the sub-objects will actually do during the test, without being tied to a particular implementation.

Ned Batchelder
++ agreed. blindly pursuing 100% coverage can result in hairy palms and an acetominphen habit. ;-)
Sky Sanders
Thank you, this gets me in the right direction.
sbenderli
+2  A: 

It is possible, it is feasible. It is also very hard to accomplish, and not everyone is sure that the benefits outweigh the costs.

In regards to achieving your specific goal - look at the ExpectedExceptionAttribute, and in your test setup the objects to throw these exceptions.

Oded
Thanks! I will look more into using the ExpectedExceptionAttribute.
sbenderli