JavaJUnit4测试用例
我需要关于为这段代码创建JUnit4测试用例的帮助
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;
}
编辑
我想要这样的东西来测试if-else语句
public class TestingTest {
@Test
public void testComputeValueTCXX() {
}
…
@Test
public void testComputeValueTCXX() {
}
}
# 1 楼答案
像这样的
确保您使用不同的输入集编写测试用例,以便覆盖静态方法的所有分支
你可以使用像EclEmma这样的插件来检查测试的覆盖率。 http://www.eclemma.org/
# 2 楼答案
让你开始的东西
首先是一个可能对“新手”更有用的“扩展”版本:
上述测试是ifs级联的第一个案例;其中assertThat是众多JUnit主张之一;而is()是一种hamcrest匹配方法。此外,以下是我编写测试用例的方式:
(主要区别在于:对我来说,单元测试不应该包含任何我不需要的信息;从这个意义上说:我希望它尽可能地纯净、简短、简洁)
基本上,你需要编写不同的测试,以覆盖贯穿逻辑的所有路径。您可以使用许多现有的coverage工具之一来确保覆盖所有路径
或者,您也可以查看parameterized测试。意思是:不要创建很多测试方法,每个方法都只是用不同的参数调用实际方法,而是将所有这些不同的“调用参数”放入一个表中;然后JUnit从该表中获取所有数据,并在调用测试中的“target”方法时使用这些数据
# 3 楼答案
假设您要测试的方法位于类Stackoverflow中。您需要一个名为StackoverflowTest的测试类。这就是它可能的样子: