I want to run selected test methods from any test class with different parameters
Ex: 1) ClassA -> Test methods A, B
@Test
public void testA(String param) {
System.out.println("From A: "+param);
}
@Test
public void testB(String param) {
}
2) ClassB -> Test methods C, D
@Test
public void testC(String param) {
System.out.println("From C: "+param);
}
@Test
public void testD(String param) {
}
From these I want to run following tests
1) testA(from ClassA) two times with diff params "test1" & "test2"
2) testC(from ClassB) two times with diff params "test3" & "test3"
Here my test count should show as '4'
Can anyone help on this...
Use Parameterized tests provided with Junits, wherein you can pass the parameters at run time.
Refer to org.junit.runners.Parameterized (JUnit 4.12 offers the possibility to parametrize with expected values and without expected values in the setup array).
Try this:
@RunWith(Parameterized.class)
public class TestA {
@Parameterized.Parameters(name = "{index}: methodA({1})")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][]{
{"From A test1", "test1"}, {"From A test2", "test2"}
});
}
private String actual;
private String expected;
public TestA(String expected,String actual) {
this.expected = expected;
this.actual = actual;
}
@Test
public void test() {
String actual = methodFromA(this.actual);
assertEquals(expected,actual);
}
private String methodFromA(String input) {
return "From A " + input;
}
}
you can write a similar test for class B.
For a test taking just single parameters, fro JUnit 4.12 you can do this:
@RunWith(Parameterized.class)
public class TestU {
/**
* Provide Iterable to list single parameters
*/
@Parameters
public static Iterable<? extends Object> data() {
return Arrays.asList("a", "b", "c");
}
/**
* This value is initialized with values from data() array
*/
@Parameter
public String x;
/**
* Run parametrized test
*/
@Test
public void testMe() {
System.out.println(x);
}
}