JUnit @Rule to pass parameter to test

I use @Parameters and @RunWith(value = Parameterized.class) for passing values to tests. An example can be found here.

I did not know about the @Rule annotation, but after reading this post, I think it serves another purpose than passing parameters to the tests:

If in your test class, you create a field pointing to an object implementing the MethodRule interface, and you mark this to be processed as a rule, by adding the @Rule implementation, then JUnit will call back on your instance for every test it will run, allowing you to add additional behavior around your test execution.

I hope this helps.


As IAdapter said you can't pass an argument using Rules, but you can do something similar.

Implement a Rule that holds all your parameter values and evaluates the test once for every parameter value and offers the values through a method, so the test can pull them from the rule.

Consider a Rule like this (pseudo code):

public class ParameterRule implements MethodRule{
    private int parameterIndex = 0;
    private List<String> parameters;
    public ParameterRule(List<String> someParameters){ 
        parameters = someParameters;
    }

    public String getParameter(){
        return parameters.get(parameterIndex);
    }

    public Statement apply(Statement st, ...){
        return new Statement{
             public void evaluate(){
                 for (int i = 0; i < parameters.size(); i++){
                     int parameterIndex = i;
                     st.evaluate()
                 }      
             }
        }
    }
}

You should be able to use this in a Test like this:

 public classs SomeTest{
     @Rule ParameterRule rule = new ParameterRule(ArrayList<String>("a","b","c"));

     public void someTest(){
         String s = rule.getParameter()

         // do some test based on s
     }
 }