Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter to @Before setup in jUnit test [duplicate]

Is there any way to avoid calling populateRandomData() method at the begining of each test without having a fixed parameter 100. I need to call the same method to setup data before execution of each test but I need to change the number of test data entries e.g. 100 in each case .

public class Tester
{

   @Before
    public void setUp() {
        populateRandomData(100)
    }

    @Test
    public void testMethod() {

    }

    private void populateRandomData(n){
        //n times insert random data in table.
    }
}
like image 272
Neil Avatar asked Oct 14 '14 09:10

Neil


1 Answers

You can create Parameterized JUnit Test which allows you to add number of parameters you want to pass in unit test case. Have a look at example tutorial Create Parameterized Test Case.

OR

@Rule, using this annotations on your test methods to parameterize the execution of your rules makes it even more useful. Taken from JUnit 4.7 @Rules

EDIT :

Example of Using @Rule :

Below is the class which allows you to initialize different value of num variable which will be used in test method :

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class Test1 implements TestRule {

    private final int   num;

    public Test1(int num) {
        this.num = num;
    }

    public int getNum() {
        return num;
    }

    public class Test1Statement extends Statement {
        private final Statement statement;

        public Test1Statement(Statement statement, int num) {
            this.statement = statement;
        }

        @Override
        public void evaluate() throws Throwable {
            statement.evaluate();
        }
    }

    @Override
    public Statement apply(Statement statement, Description description) {
        return new Test1Statement(statement, num);
    }
}

The class below is the actual test case class. It contains JUnit test cases & set value of num variable in test method.

import org.junit.Rule;
import org.junit.Test;

public class RuleNumberTester {

    @Rule
    public Test1    test    = null;

    @Rule
    public Test1    test1   = null;

    @Test
    public void num1Test() {
        test = new Test1(111);
        System.out.println("Num 1 : " + test.getNum());
    }

    @Test
    public void num2Test() {
        test1 = new Test1(222);
        System.out.println("Num 2 : " + test1.getNum());
    }
}

Output :

Test cases are executed successfully & shows the values of num variable which was initialized in test methods on console.

Num 1 : 111
Num 2 : 222
like image 70
OO7 Avatar answered Sep 30 '22 17:09

OO7