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

1.7k views Asked by At

I am writing a JUnit test case. I want to initialize a list objects. For brevity, let's initialize a list of String objects:

public class MyTest {
    @Rule
    public List<MySQLContainer> tests = Arrays.asList(new MySQLContainer("5.5"), new MySQLContainer("5.6"));

    @Test
    public void myTest() {

    }
}

When executing, I get the following runtime error:

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

I don't get such error when I simply initialize a MySQLContainer instead of List<MySQLContainer>.

Why is this not working? How can I fix it?

I have JUnit 4.12 in my dependencies.

3

There are 3 answers

5
Mureinik On BEST ANSWER

@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...    
    }
}
0
Sox - On

Try using ArrayList()

    public List<MySQLContainer> tests = new ArrayList();
0
Stefan Birkner On

Remove the @Rule and everything is fine.

public class MyTest {

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

    @Test
    public void myTest() {

    }
}

@Rule is used for JUnit 4 extensions and make it possible to do some more complex things.