【问题标题】:Why is Code Coverage not reporting 100% code coverage in test code when checking for exceptions?为什么代码覆盖率在检查异常时未报告测试代码中的 100% 代码覆盖率?
【发布时间】:2014-06-10 23:04:09
【问题描述】:

考虑以下代码:

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();
    }
}

为什么代码覆盖率报告测试方法没有 100% 覆盖?

回答:

没有覆盖右大括号,因为代码总是会抛出异常并且永远不会到达方法的末尾。

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

看来,要获得 100% 的覆盖率,您需要排除检查异常的测试方法。烦人。

EDIT1:删除了不相关的流利断言。 EDIT2:删除了不相关的泛型。

【问题讨论】:

  • 出于好奇,如果您手动调用Action,它会被拾取吗?当在反射中调用任何内容或未在您的代码中专门调用任何内容时,代码覆盖工具就会丢失。
  • 我更新了问题,似乎与流利的断言无关。

标签: c# .net code-coverage mstest


【解决方案1】:

没有覆盖右大括号,因为代码总是会抛出异常并且永远不会到达方法的末尾。

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

看来,要获得 100% 的覆盖率,您需要排除检查异常的测试方法。烦人。

【讨论】:

    【解决方案2】:

    将代码转换为如下所示,当然如果它是一行。

    public IConverter GetConverter() throw new ArgumentException();
    

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 1970-01-01
      • 2012-01-18
      • 2023-03-21
      • 1970-01-01
      • 2014-08-21
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      相关资源
      最近更新 更多