我有这个 if-else 语句,我想编写一个 J 单元测试来测试每一行以查看是否正确。有什么想法吗?
public class Testings {
public static int computeValue(int x, int y, int z) {
int value = 0;
if ( x == y )
value = x + 1;
else if (( x > y) && ( z == 0))
value = y + 2;
else
value = z;
return value;
}
}
最佳答案
使用涵盖所有情况的值测试您的方法:
- x == y
- x != y and x > y and z == 0
- x != y and x > y and z != 0
- x != y and x < y and z == 0
- x != y and x < y and z != 0
- x == y 和 z != 0
- x == y 和 z == 0
例子:
assertEquals(4, Testings.computeValue(3, 3, 10)); // x == y
assertEquals(7, Testings.computeValue(10, 5, 0)); // x != y and x > y and z == 0
assertEquals(1, Testings.computeValue(10, 5, 1)); // x != y and x > y and z != 0
...
此外,每个测试方法都应该有一个断言,这样您就可以给它一个合适的名称:
@Test
public void testXEqualY(){
int x=3, y=3, z=10;
assertEquals(4, Testings.computeValue(x, y, z));
}
关于java - 如何使用 J-unit 测试简单的 if else 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41340467/