How to Dynamically Create a Test Suite in Junit 4

How do I Dynamically create a Test Suite in JUnit 4?

I found Classpath suite quite useful when used with a naming convention on my test classes.

https://github.com/takari/takari-cpsuite

Here is an example:

import org.junit.extensions.cpsuite.ClasspathSuite;
import org.junit.runner.RunWith;

@RunWith(ClasspathSuite.class)
@ClassnameFilters({".*UnitTest"})
public class MySuite {
}

Junit4: how to create test suite dynamically

The cpsuite project uses a custom annotation to determine the tests to run at runtime based on patterns. This isn't what you want, but it is a good start. You can take the source code for it and replace the "find tests" part with reading from your property file.

Note that the annotation/code is different for different versions of JUnit 4.X. If you are still on JUnit 4.4 or below, you'll need the older one.

JUnit test with dynamic number of tests

Take a look at Parameterized Tests in JUnit 4.

Actually I did this a few days ago. I'll try to explain ...

First build your test class normally, as you where just testing with one input file.
Decorate your class with:

@RunWith(Parameterized.class)

Build one constructor that takes the input that will change in every test call (in this case it may be the file itself)

Then, build a static method that will return a Collection of arrays. Each array in the collection will contain the input arguments for your class constructor e.g. the file. Decorate this method with:

@Parameters

Here's a sample class.

@RunWith(Parameterized.class)
public class ParameterizedTest {

private File file;

public ParameterizedTest(File file) {
this.file = file;
}

@Test
public void test1() throws Exception { }

@Test
public void test2() throws Exception { }

@Parameters
public static Collection<Object[]> data() {
// load the files as you want
Object[] fileArg1 = new Object[] { new File("path1") };
Object[] fileArg2 = new Object[] { new File("path2") };

Collection<Object[]> data = new ArrayList<Object[]>();
data.add(fileArg1);
data.add(fileArg2);
return data;
}
}

Also check this example

Adding a @Test method dynamically to junit test class

In JUnit 4 there is a concept called "Parameterized Test" that is used for exactly this.

I don't fully understand your test above, but this should give you a hint:

@RunWith(Parameterized.class)
public class ParameterizedTest {

private String query;
private String expectedResult;

public ParameterizedTest(String query, String expectedResult) {
this.query = datum;
this.expectedResult = expectedResult;
}

@Parameters
public static Collection<Object[]> generateData() {
Object[][] data = {
{ "a:120", "result1" },
{ "b:220", "result2" },
};
return Arrays.asList(data);
}

@Test
public void checkQueryResult() {
System.out.println("Checking that the resutl for query " + query + " is " + expectedResult);
// ...
}

}


Related Topics



Leave a reply



Submit