Search code examples
c#.netcode-coveragemstest

Why is Code Coverage not reporting 100% code coverage in test code when checking for exceptions?


Consider the following code:

public interface IConverter
{
}

public class ConverterFactory
{
    public IConverter GetConverter()
    {
        throw new ArgumentException();
    }
}

[TestClass]
public class ConverterFactoryTests
{
    [TestMethod]
    [ExpectedException(typeof(ArgumentException))]
    public void GetConverterShouldThrowExceptionWhenConverterNotRegistered()
    {
        var factory = new ConverterFactory();
        factory.GetConverter();
    }
}

Why is code coverage reporting that the test method is not 100% covered?

ANSWER:

The closing curly bracket is not covered as the code will always throw an exception and never get to the end of the method.

How do I obtain 100% coverage when an exception is thrown in a unit test?

So it appears that to get 100% coverage you would need to exclude test methods that check exceptions. Annoying.

EDIT1: Removed fluent assertions as not relevant. EDIT2: Removed generics as not relevant.


Solution

  • The closing curly bracket is not covered as the code will always throw an exception and never get to the end of the method.

    How do I obtain 100% coverage when an exception is thrown in a unit test?

    So it appears that to get 100% coverage you would need to exclude test methods that check exceptions. Annoying.