【问题标题】:cyclomatic complexity of the pseudo-code伪代码的圈复杂度
【发布时间】:2013-07-21 11:04:37
【问题描述】:

圈复杂度是实现对特定模块的全面测试覆盖所必需的测试用例数量。

考虑以下伪代码:

If (A > B) and (C > D) then
    A = A + 1
    B = B + 1
Endif

我认为这里只需要两个测试用例,一个为真条件另一个为假条件,所以圈复杂度应该是 2 但答案是 3(不知道为什么)。

请有人帮我理解为什么答案是 3 而不是 2。

【问题讨论】:

  • 这个问题似乎是题外话,因为它是关于计算机科学的,还有其他网站。

标签: algorithm cyclomatic-complexity


【解决方案1】:

圈复杂度直接衡量通过程序源代码的线性独立路径的数量。

If (A > B) and (C > D) then
    A = A + 1
    B = B + 1
Endif

案例 1。

If (true) and (true) then
    // Execute some code
Endif

案例 2。

If (true) and (false) then
    // Don't execute code
Endif

案例 3。

If (false) and (2nd part won't be executed) then
    // Don't execute code
Endif

所以圈复杂度将是 3。

【讨论】:

    【解决方案2】:

    编译器会将代码翻译成类似以下的伪汇编代码:

    A - B
    branch if greater then 0 to end
    C - D
    branch if greater then 0 to end
    inc A
    inc B
    end:
    ...
    

    现在,为了在所有分支中做出所有可能的选择,您需要 3 个测试用例:

    1. A
    2. C
    3. A > B 和 C > D(不要在第 2 条分支指令中分支,而是进入递增指令)

    请注意,对于“覆盖”的替代定义 - “所有指令覆盖”,1 个测试用例就足够了(使用上面的编译代码),因为即使你不分支,“分支 if..”指令仍在执行,因此对于 A>B 和 C>D 测试用例,您实际上会执行所有指令。


    附:假设在这里:

    圈复杂度是测试用例所需的数量 实现对特定模块的全面测试覆盖。

    【讨论】:

    • 作者特意问的是“圈复杂度”。
    • @simonzack: Cyclomatic complexity is number of test cases that are necessary to achieve thorough test coverage of a particular module. 答案旨在表明您需要 3 个测试用例来覆盖该模块。现在,什么是“覆盖”可能是多种多样的,我在这里假设“所有分支覆盖”。
    猜你喜欢
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多