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

Initialize a List<?> in a JUnit via @Rule

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

尝试使用 ArrayList()

    public List<MySQLContainer> tests = new ArrayList();

@Rules are for executing code before each test method. If you just need to initialize a member, put this initialization in a method annotated with @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...    
    }
}

删除@Rule,一切正常。

public class MyTest {

    private final List<MySQLContainer> tests = Arrays.asList(
        new MySQLContainer("5.5"),
        new MySQLContainer("5.6")
    );

    @Test
    public void myTest() {

    }
}

@Rule 用于 JUnit 4 扩展,可以做一些更复杂的事情。