Search code examples
c#unit-testingmstestcustom-exceptions

Unit test a custom Exception


My code coverage has listed my custom exception as 0 test coverage. I am using MsTest,Moq and Fluentassertions. Is there an appropriate unit test for a custom exception?

Here is my Exception class

  public class ConfigurationNotFoundException : Exception
    {
        public ConfigurationNotFoundException()
        {
        }

        public ConfigurationNotFoundException(string message) : base(message)
        {
        }

        public ConfigurationNotFoundException(string message, Exception innerException) : base(message, innerException)
        {
        }

        protected ConfigurationNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }

Solution

  • If it's showing as 0% coverage, it's because it is unused/untested.

    Taking your original custom exception class, and this beautiful class which uses it :

    public class SomeClass
    {
        public void SomeMethod()
        {
            throw new ConfigurationNotFoundException("Hey!");
        }
    }
    

    If I have the following Unit Test (with Fluent Assertions) :

    [TestClass]
    public class SomeClassTest
    {
        [TestMethod]
        public void SomeMethodShouldThrow()
        {
            Action invocation = () => new SomeClass().SomeMethod();
    
            invocation.ShouldThrow<ConfigurationNotFoundException>().WithMessage("Hey!");
        }
    }
    

    The coverage shows correctly the used constructor as covered :

    Coverage result


    So if it's not covered, it is either untested or unused.

    To verify if it is unused, you can do a right-click on the method name and select 'Find Usages'. If you have the 'No usages' message, you can safely delete it.

    If it is used but untested; test it (the behavior, not the exception class itself).


    With our previous example, you'd only need the following :

    public class ConfigurationNotFoundException : Exception
    {
        public ConfigurationNotFoundException(string message)
            : base(message)
        {
        }
    }
    

    The other constructors are not needed to inherit from Exception, and would only clutter the class since they serve no purpose.