Parameterised test in JUnit

newtoprogramming picture newtoprogramming · Apr 28, 2013 · Viewed 8.5k times · Source

I have a program, containing 3 parameterized methods, that receives arguments from the command line. I would like to test them and I have written a test in JUnit, by right clicking on the original class and clicking new Junit test. In the test class, I have annotated the class, as @RunWith(Parameterized.class), and the parameterized methods, as @Parameters and the testmain method as @test.

In each method, I have created a reference for the original class and I have called the methods and passed the required parameters. Now the there is an Initialization error, that says there are no public static methods in the test class. Can someone advise me if this is the right way to carry out a test and if not, what is the right way to do it.

Just to make myself clear, I shall also give an example of what I have done so far (this is not the original code.)

@RunWith(Parameterized.class)
Public class customertest(){

@Parameters
public testmethod1(String a, String b){
customer test = new customer();
test.method1(a, b);
}

@Parameters
public testmethod2(String c, String d){
customer test = new customer();
test.method2(c, d);
}

@parameters
public testmethod3(String e){
customer test = new customer();
test.method3(e);

}

@Test
public static void testmain(String [] args){
customertest tester = new customertest();
tester.testmethod1(args[0], args[1]);
tester.testmethod2(args[2], args[3]);
tester.testmethod3(args[4]);


}




}

Answer

John B picture John B · Apr 29, 2013

You are using @Parameters completely wrong (in fact what you have in not valid Java syntax as the methods testmethodsx do not have return values).

See the example at this site.

There should be only one @Parameters method. It should be static and return a Collection<Object[]>. The number of elements in the array must be equal to the number of arguments in the test class' constructor.

In the example you will see that FibonacciTest has a constructor that takes 2 arguments. Each array returned by the @Parameteres method contains 2 elements. These elements are passed to the constructor and the tests should use the fields to make parameter-specific tests.