我有一个有趣的要求。我希望在我的应用程序中拥有尽可能更好的测试用例覆盖率。我正在使用参数化 Junit 来运行具有多个不同输入的测试用例。我的示例测试类如下所示:
@Parameters
public static Collection<Object[]> testInputs()
{
return Arrays.asList({
{1, CoreMatchers.is(1)},
{2, CoreMatchers.is(2)}
});
}
@Test
public test()
{
myApp.run();
assertThat(myApp.getA(), matcher);
}
这样,我就用测试参数定义了断言逻辑。现在我想在测试用例上运行多个匹配器,其中一些可以是我编写的自定义匹配器。
@Parameters
public static Collection<Object[]> testInputs()
{
return Arrays.asList({
{1, Arrays.asList( CoreMatchers.is(1), CustomMatchers.status(1) ) },
{2, Arrays.asList( CoreMatchers.is(2), CustomMatchers.status(2) ) }
});
}
断言就像:
for(Matcher<MyApp> matcher: matchers)
{
assertThat(myApp, matcher);
}
但问题是,两个匹配器都运行在不同的对象上。我定义 CustomMatcher 的最佳方式是什么?
我应该按匹配器类型对断言进行分类吗?
如果有任何帮助,我将不胜感激。提前致谢。
最佳答案
我不确定“两个匹配器在不同的对象上运行”是什么意思,但您可以使用 CoreMatchers.allOf
将匹配器组合起来进行单个测试运行。 。这样您就不需要循环匹配器列表,并且可以传递任意数量的匹配器,包括一个。
@Parameters
public static Collection<Object[]> testInputs()
{
return Arrays.asList({
{1, CoreMatchers.allOf( CoreMatchers.is(1), CustomMatchers.status(1) ) },
{2, CoreMatchers.allOf( CoreMatchers.is(2), CustomMatchers.status(2) ) }
});
}
关于java - 编写更好的 JUnit 参数化测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12421582/