How to get 100% coverage when an exception is thrown in unit test?

In C#you can catch the exception in the default test suite, like this:

[TestMethod]
[ExpectedException(typeof (ArgumentNullException))]
public void TestNullComposite()
{
    IApi api = new Api();
    api.GetDataUsingDataContract(null); // this method throws ArgumentNullException
}

But when you analyze the code coverage, it says that you get only 66.67% of the coverage because the last curly bracket was not covered.

How can I achieve 100% coverage of this unit test?

+4
source share
3 answers

In NUnit , you have a method Assert.Throws<Exception>()that checks if the desired exception has been thrown. It also returns this exception as a return value so that you can get additional statements if you want:

[Test]
public void Api_GetDataUsingDataContractWithNullParameter_ThrowsArgumentNullException()
{
    var api = new Api();
    var exception = Assert.Throws<ArgumentNullException>(() => api.GetDataUsingDataContract(null));
    Assert.That(exception.Message, Is.Not.Null.Or.Empty);
    Assert.That(exception.Message, Is.StringContaining("source"));
}

- , , 100%.

+3

, , , , .

, 100% .

. , .

, , , , . - ( , , ):

[TestMethod]
public void TestNullComposite()
{
    IApi api = new Api();
    bool didThrow = false;
    try
    {
        api.GetDataUsingDataContract(null); // this method throws ArgumentNullException
    }
    catch(ArgumentNullException) 
    {
        didThrow = true;
    }
    Assert.IsTrue(didThrow);
}

. .

+6

, . , Cover Code.

Just decorate your [TestClass] attribute with [ExcludeFromCodeCoverage] !

Thus, it is theoretically possible to achieve 100% SS.

+1
source

Source: https://habr.com/ru/post/1543628/


All Articles