需要更好的 jUnit 测试覆盖率
大家晚上好
假设你的代码有以下语句:
if (string ends with char 'y') {
if ((char before last is not 'e') || (char before last is not 'a')) {
return (something awesome);
}
}
所以我认为这很简单......
测试1: 输入=“xy”(最后一个字符是y,最后一个字符之前的字符不是e或a)
结果-部分覆盖...
我还缺少哪些其他测试?如果这是 and &&我认为测试会比 || 更容易,但是 ||我有点困惑。
你能建议测试2,3,n吗?
谢谢
Good evening everyone
Suppose your code has the following statement:
if (string ends with char 'y') {
if ((char before last is not 'e') || (char before last is not 'a')) {
return (something awesome);
}
}
So that's simple enough i thought ...
Test1:
input = "xy" (last char is y, char before last is not e or a)
Result - partial coverage ...
What other tests i am missing? If this was and && instead of ||, i suppose test would be far easier, but || confused me a bit.
Can you suggest Test2,3,n?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您想要使用输入“ey”和“ay”测试预期行为。
您可能会发现您的方法并没有达到您的预期。我认为
||
确实让你有点困惑。You want to test for the expected behavior with inputs "ey" and "ay".
You may find that your method is not doing quite what you think it is. I think
||
has indeed confused you a bit.您还可以编写测试来确保您不会返回很棒的东西
。测试应该证明您的预期行为。
那么不同长度的字符串呢?
您可能希望将其转换为方法或函数,并为其命名适当的名称。
然后为这个简单的方法编写测试(在 TDD 中,您将首先编写它们)。
You can also write tests to make sure you don't return something awesome
The tests should prove your intended behaviour.
What about various lengths of strings?
You may want to turn this into a method or function and name it something appropriate.
Then write the tests for this simple method (in TDD you would write them first).
有不同类型的覆盖:
我认为您的困惑在于之所以玩,是因为您正在考虑符号覆盖范围,而您的工具则为您提供分支覆盖范围。区别如下:
符号覆盖率将衡量您是否已到达每个符号(即直到“;”字符的代码串)。下面一行包含两个符号:
int i = 0;整数 j = 3;
分支覆盖率衡量每个条件的真值和假值。在您的示例中,列出了 4 个不同的条件,每个条件都有一个 true 分支和一个 false 分支。为了充分测试每个分支,您需要对以下每个条件进行测试:
根据您编写的代码,您可能会遇到意想不到的情况。如果字符串以 y 结尾,无论怎样,你都会得到 Something_awesome。如果字符串以“ey”结尾,则它不是以“ay”结尾。如果其中任何一个条件成立,您就会得到一些很棒的东西。编写测试并亲自查看。
There's different types of coverage:
I think your confusion is coming in to play because you are thinking in terms of symbol coverage while your tool is giving you branch coverage. Here's the distinction:
Symbol coverage will measure whether you have reached each symbol (i.e. bunch of code up to a ';' character). The below line contains two symbols:
int i = 0; int j = 3;
Branch coverage measures each condition in both the true and false values. In your example you had 4 different conditions listed, each of which have a true branch and a false branch. In order to fully test each branch, you need a test for each of the following conditions:
With the code you wrote, you will probably experience something unexpected. You will get something_awesome no matter what if the string ends in y. If the string ends with 'ey', then it is not ending with 'ay'. If either of those conditions are true you get something awesome. Write the tests and see for yourself.