Search code examples
javajunitjunit4junit-rule

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


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.


Solution

  • @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...    
        }
    }