我正在编写一个JUnit测试用例。我想初始化一个列表对象。为简便起见,让我们初始化String
对象的列表:
public class MyTest {
@Rule
public List<MySQLContainer> tests = Arrays.asList(new MySQLContainer("5.5"), new MySQLContainer("5.6"));
@Test
public void myTest() {
}
}
执行时,出现以下运行时错误:
org.junit.internal.runners.rules.ValidationError: The @Rule 'tests' must implement MethodRule or TestRule.
at org.junit.internal.runners.rules.RuleMemberValidator$FieldMustBeARule.validate(RuleMemberValidator.java:234)
at org.junit.internal.runners.rules.RuleMemberValidator.validateMember(RuleMemberValidator.java:99)
at org.junit.internal.runners.rules.RuleMemberValidator.validate(RuleMemberValidator.java:93)
at org.junit.runners.BlockJUnit4ClassRunner.validateFields(BlockJUnit4ClassRunner.java:196)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:1
仅初始化MySQLContainer
而不是List<MySQLContainer>
时,不会出现此类错误。
为什么这不起作用?我该如何解决?
我的依赖项中包含JUnit 4.12。
答案 0 :(得分:2)
尝试使用ArrayList()
public List<MySQLContainer> tests = new ArrayList();
答案 1 :(得分:1)
@Rule
用于在每种测试方法之前执行代码。如果您只需要初始化成员,请将此初始化放入带有@Before
注释的方法中:
public class MyTest {
private List<MySQLContainer> containers;
@Before
public void initContainers() {
containers = = Arrays.asList(new MySQLContainer("5.5"), new MySQLContainer("5.6"));
}
@Test
public void myTest() {
// Some test...
}
}
答案 2 :(得分:0)
删除employeeID || category || endDate
1 || Drivers License || 2019-01-01
1 || Medical Examiners Certificate || 2019-01-01
2 || Drivers License || 2016-01-01
2 || Medical Examiners Certificate || 2020-01-01
,一切正常。
@Rule
public class MyTest {
private final List<MySQLContainer> tests = Arrays.asList(
new MySQLContainer("5.5"),
new MySQLContainer("5.6")
);
@Test
public void myTest() {
}
}
用于JUnit 4扩展,可以做一些更复杂的事情。