Junit 4中的@parameters
-
05-07-2019 - |
题
在使用参数化类运行的junit测试类中,我可以使用多个@Parameters方法吗?
@RunWith(value = Parameterized.class)
public class JunitTest6 {
private String str;
public JunitTest6(String region, String coverageKind,
String majorClass, Integer vehicleAge, BigDecimal factor) {
this.str = region;
}
@Parameters
public static Collection<Object[]> data1() {
Object[][] data = {{some data}}
return Arrays.asList(data);
}
@Test
public void pushTest() {
System.out.println("Parameterized str is : " + str);
str = null;
}
@Parameters
public static Collection<Object[]> data() {
Object[][] data = {{some other data}}
return Arrays.asList(data);
}
@Test
public void pullTest() {
System.out.println("Parameterized new str is : " + str);
str = null;
}
}
解决方案
您可以使用 Theories runner(搜索理论一词)该链接)将不同的参数传递给不同的方法。
其他提示
可能是 data1
方法,但不能保证,它会使用JVM首先给出junit4的那个。
以下是junit的相关代码:
private FrameworkMethod getParametersMethod(TestClass testClass) throws Exception {
List<FrameworkMethod> methods= testClass.getAnnotatedMethods(Parameters.class);
for (FrameworkMethod each : methods) {
int modifiers= each.getMethod().getModifiers();
if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))
return each;
}
throw new Exception("No public static parameters method on class " + testClass.getName());
}
因此,它将使用它找到的第一个公共静态注释方法,但它可以按任何顺序找到它们。
你为什么要用这种方式编写测试?您应该只有一个 @Parameters
-annotated方法。
未指定具有多种数据方法。您可以在 skaffman的回答中看到它。
为什么没有提供实现两种数据方法?
答案可能是:耦合。
将此测试分成两个测试用例是否过于复杂?您将能够引入一个小的继承并共享常用方法。使用两个测试用例,您可以提供两种独立的数据方法并很好地测试您的内容。
我希望它有所帮助。
您可以为操作相同参数的每组方法创建内部类。例如:
public class JunitTest6 {
@RunWith(value = Parameterized.class)
public static class PushTest{
private String str;
public PushTest(String region) {
this.str = region;
}
@Parameters
public static Collection<Object[]> data() {
Object[][] data = {{some data}}
return Arrays.asList(data);
}
@Test
public void pushTest() {
System.out.println("Parameterized str is : " + str);
str = null;
}
}
@RunWith(value = Parameterized.class)
public static class PullTest{
private String str;
public PullTest(String region) {
this.str = region;
}
@Parameters
public static Collection<Object[]> data() {
Object[][] data = {{some other data}}
return Arrays.asList(data);
}
@Test
public void pullTest() {
System.out.println("Parameterized new str is : " + str);
str = null;
}
}
}
不隶属于 StackOverflow