猿问

通过@Rule 在 JUnit 中初始化 List<?>

我正在编写一个 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

当我简单地初始化 aMySQLContainer而不是List<MySQLContainer>.


为什么这不起作用?我该如何解决?


我的依赖项中有 JUnit 4.12。


泛舟湖上清波郎朗
浏览 145回答 3
3回答

撒科打诨

@Rules 用于在每个测试方法之前执行代码。如果你只需要初始化一个成员,把这个初始化放在一个用@Before以下注释的方法中:public class MyTest {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; private List<MySQLContainer> containers;&nbsp; &nbsp; @Before&nbsp; &nbsp; public void initContainers() {&nbsp; &nbsp; &nbsp; &nbsp; containers =&nbsp; = Arrays.asList(new MySQLContainer("5.5"), new MySQLContainer("5.6"));&nbsp; &nbsp; }&nbsp; &nbsp; @Test&nbsp; &nbsp; public void myTest() {&nbsp; &nbsp; &nbsp; &nbsp; // Some test...&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }}

MMMHUHU

尝试使用 ArrayList()&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;List<MySQLContainer>&nbsp;tests&nbsp;=&nbsp;new&nbsp;ArrayList();

月关宝盒

删除@Rule,一切都很好。public class MyTest {&nbsp; &nbsp; private final List<MySQLContainer> tests = Arrays.asList(&nbsp; &nbsp; &nbsp; &nbsp; new MySQLContainer("5.5"),&nbsp; &nbsp; &nbsp; &nbsp; new MySQLContainer("5.6")&nbsp; &nbsp; );&nbsp; &nbsp; @Test&nbsp; &nbsp; public void myTest() {&nbsp; &nbsp; }}@Rule 用于 JUnit 4 扩展,可以做一些更复杂的事情。
随时随地看视频慕课网APP

相关分类

Java
我要回答