Posts Tagged ‘junit’
Integration testing with JUnit4
Performing a jUnit4 tests sequence in order to get integration testing results can be achieved by implementing a simple abstract class.
import java.util.Arrays;
import java.util.LinkedHashMap;
import org.junit.runner.JUnitCore;
import org.junit.runner.Request;
import org.junit.runner.Result;
public abstract class AbstractTestSuite {
/**
* Tests to be launched
* Object - JUnit test object
* String[] - Object method to be tested
*/
protected LinkedHashMap<object , String[]> tests = new LinkedHashMap</object><object , String[]>();
/**
* Tests to be launched
* <code>
* tests.put(new JUnitTest1(), new String[]{"testInvoke", "testInvokeValidateResult"});
* tests.put(new JUnitTest2(), new String[]{"testInvoke"});
* ...
* </code>
*/
protected abstract void init();
/**
* Tests execution.
* Declaration order of Junit test objects and methods is followed.
*/
public void runTests() {
init();
for (Object testObject: tests.keySet()) {
for (String test: tests.get(testObject)) {
Request request = Request.method(testObject.getClass(), test);
Result result = new JUnitCore().run(request);
if (result.getFailureCount() > 0) {
System.err.println(Arrays.asList(result.getFailures()));
}
}
}
}
}
Extending AbstractTestSuite class allows to define tests sequence including even the same jUnit class in different places of the sequence.
public class JUnitTests extends AbstractTestSuite {
protected void init() {
tests.put(new JUnitTest1(), new String[]{"testInvoke", "testInvokeValidateResult"});
tests.put(new JUnitTest2(), new String[]{"testInvoke"});
tests.put(new JUnitTest1(), new String[]{"testInvokeOther"});
}
public static void main(String... args) throws Exception {
new JUnitTests().runTests();
}
}