gpt4 book ai didi

unit-testing - 圈复杂度计算——具体例子

转载 作者:行者123 更新时间:2023-11-28 20:22:46 25 4
gpt4 key购买 nike

假设我们有以下代码:

public void testIt(boolean a, boolean b){
if (a){
...
}
if (b){
....
}
}

据我所知,有三种计算方法。我将使用其中两个:区域公式和经验法则。

使用区域公式我们有两个区域 if(a){this is the first one}if (b) {this is the second}。所以 CC = 两个区域 +1 = 3。

经验法则来自Testing for ISTQB Advanced Level Technical Test Analyst vol 3一书:

Now, this is all simple enough for a small, modest method like this. For larger functions, drawing the graph and doing the calculation from it can be really painful. So, a simple rule of thumb is this: Count the branching and looping constructs and add 1. The if statements, for, while, and do/while constructs, each count as one. For the switch/case constructs, each case block counts as one. In if and ladder if constructs, the final else does not count. For switch/case constructs, the default block does not count. This is a rule of thumb, but it usually seems to work.

所以根据这个规则CC = two if conditions +1 =3.

然而,在与一位用户聊天的 stackoverflow 上,有人说这段代码的 CC = 4(他使用了第三种方法),并提供了该用户提供的以下图片: enter image description here

那么这段代码的圈复杂度是多少呢? 3 或 4 还是?

最佳答案

根据 definition,此代码的圈复杂度为 3

M = E − N + 2P,

where

E = the number of edges of the graph.
N = the number of nodes of the graph.
P = the number of connected components.

M = 7 - 6 + 1*2 = 3

就软件测试而言,它意味着:

M is an upper bound for the number of test cases that are necessary to achieve a complete branch coverage.

M is a lower bound for the number of paths through the control flow graph (CFG).

All three of the above numbers may be equal: branch coverage <= cyclomatic complexity <= number of paths.

因此,您需要 2 个测试来提供分支覆盖。但这并不意味着它会覆盖所有路径。

要覆盖此处的所有路径,您需要进行 4 次测试。

要理解它,请考虑对您的代码进行以下更新:

public String testIt(boolean a, boolean b){
String s = "";
if (a) s = s+"a";
if (b) s = s+"b";
return s;
}

覆盖两个分支你可以测试 (true,true) 和 (false,false)

但是可能路径(结果)的数量是 4:

"", "a", "b", "ab"

上面的公式绝对没问题2 <= 3 <= 4

关于unit-testing - 圈复杂度计算——具体例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36580257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com