在 C#中,您可以在默认测试套件中捕获如下异常:
In C# you can catch an 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 }但是,当您分析代码覆盖率时,它说您只得到66.67%的覆盖率,因为最后一个花括号没有被覆盖.
But when you analyze the code coverage, it says that you only get 66.67% coverage because the last curly brace was not covered.
在该单元测试中,我将如何实现100%的覆盖率?
How would I go about achieving 100% coverage on this unit test?
推荐答案在 NUnit 您有方法 Assert.Throws< Exception>() ,它检查是否抛出了所需的异常.它还会将该异常作为返回值返回,以便您可以根据需要进一步声明:
Within NUnit you have a method Assert.Throws<Exception>(), which checks if the desired exception was thrown. It also returns that exception as return value, so that you could have further assertations if you like:
[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%.
Due to the fact, that the method does not throw by itself, your coverage would be 100%.
更多推荐
在单元测试中引发异常时,如何获得100%的覆盖率?
发布评论