Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit @Rule to pass parameter to test

I'd like to create @Rule to be able to do something like this

@Test public void testValidationDefault(int i) throws Throwable {..}

Where i is parameter passed to the test by @Rule.

However I do get

java.lang.Exception: Method testValidationDefault should have no parameters

is there any way to bypass it and set the i parameter in the @Rule?

like image 950
IAdapter Avatar asked Jun 17 '10 10:06

IAdapter


2 Answers

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
     }
 }
like image 187
Jens Schauder Avatar answered Sep 28 '22 23:09

Jens Schauder


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.

like image 22
MarcoS Avatar answered Sep 28 '22 23:09

MarcoS