单元测试代码覆盖率

时间:2014-12-11 14:26:56

标签: c# unit-testing visual-studio-2013 code-coverage

我对代码覆盖率感到有点困惑。

实施例: 我有一个方法,它有多个if语句(非嵌套),每个语句附加到我完成后返回的字符串。

我的单元测试只检查初始结果和最终结果,这是我故意为了这个问题而做的事情。介于两者之间(所以不检查else语句)

问题: 如果我运行该测试,我将获得100%的代码覆盖率。我理解这个问题的原因是我想要方法本身的代码覆盖,而不是我的测试有多少被击中。它应该有点低,因为else语句没有被命中。

我查看过有关单元测试和代码覆盖的各种教程和msdn。在某些情况下,测试似乎是分析方法本身的代码(我想做什么),但在大多数其他情况下,它只检查代码覆盖率的测试。

我的问题是; 有没有办法将测试链接到方法,以便在分析测试代码覆盖率时获取方法的代码覆盖率,或者这是代码覆盖的意图,用户必须编写测试来解释这些分支?

感谢您的时间。

编辑:代码示例。

public static string testingString(string s1, string s2, bool isAllowed, bool isAdmin, bool isCustomer){
    string result = string.Format("{0}/{1}", s1, s2);
    if (isAllowed) result += "/Allowed";
    if (isAdmin) result += "/admin";
    if (isCustomer) result += "/customer";
    return result;
}

测试:

[TestMethod]
public void testingString_BasicTest()
{
    var result = testingString("test1", "test2", false, false, false);
    var expectedResult = string.Format("{0}/{1}", "test1", "test2");

    Debug.WriteLine("Result should be: " + expectedResult);
    Assert.AreEqual(expectedResult, url);
}
尽管没有达到3 if语句结果,

testingString_BasicTest在这种情况下将具有100%的代码覆盖率。

2 个答案:

答案 0 :(得分:1)

代码覆盖率是指在测试执行中执行代码。它实际上与测试的内容没有任何关系,只是在测试运行时它会在某个时刻执行。

如果在测试过程中的任何时候执行该方法中的每个命令,代码覆盖率将返回100%。如果要查看单个测试的代码覆盖率(使用VS 2013 Ultimate代码覆盖率工具),请在“测试管理器”窗口中选择它,然后单击“测试/分析代码覆盖率/选定测试”以查看特定测试涵盖的内容。

答案 1 :(得分:-1)

鉴于您的更新,由于您构建代码的方式,您获得了100%的覆盖率。虽然并非所有代码路径都被执行,但所有行都被命中。如果您像这样重构代码,那么您将不再获得100%的覆盖率:

public static string testingString(string s1, string s2, bool isAllowed, bool isAdmin, bool isCustomer){
    string result = string.Format("{0}/{1}", s1, s2);
    if (isAllowed) 
    {
        result += "/Allowed";
    }
    if (isAdmin) 
    {
        result += "/admin";
    }
    if (isCustomer) 
    {
        result += "/customer";
    }
    return result;
}

有些工具会比其他工具更好地处理这个问题(我相信JetBrains dotCover不会报告您的版本),但有些工具只是看看执行的代码是否在线上,因为它似乎是Visual Studio工具所做的,所以它看到正在执行if()并认为整条线都被覆盖了。