Running a JUnit4 test - from a java program
I was wondering how to run some JUnit4 test inside a java program. Basically - depending on some conditions during runtime I need to decide which test runner to use. Using Junit3 I could override runTest method from TestCase class - but in JUnit4 tests do开发者_开发技巧 not extend TestCase class so I have nothing to override... Is there maybe some method that I need to implement... or sth else...
Here's some sample code for you:
public void checkTests() throws org.junit.runners.model.InitializationError {
checkTestClass((Class<?>) MyTestClss.class);
}
private void checkTestClass(Class<?> theClass) throws InitializationError {
final RunNotifier notifier = new RunNotifier();
notifier.addListener(new RunListener() {
@Override
public void testFailure(Failure failure) throws Exception {
Assert.fail(failure.getMessage());
}
});
final Runner runner = new BlockJUnit4ClassRunner(theClass);
runner.run(notifier);
}
The problem I have is that I have to run a method (which cannot be static) before each test case
If this non-static method is something related to pre-conditioning the test case, you could achieve this by annotating a method using @Before
in you test class. Take a look at the Junit4 docs for the behavior of @Before
.
Otherwise, to simply trigger a Junit test class, you can use the following code:
Runner r =
try {
r = new BlockJUnit4ClassRunner(Class.forName(testClass));
} catch (ClassNotFoundException | InitializationError e) { // FIX if necessary: JDK 7 syntax
// handle
}
JUnitCore c = new JUnitCore();
c.run(Request.runner(r));
Hope that helps.
精彩评论