问题
I have looked at all the similar questions, but in my opinion, none of them give a solid answer to this. I have a test class (JUnit 4 but also interested in JUnit 3) and I want to run individual test methods from within those classes programmatically/dynamically (not from the command line). Say, there are 5 test methods but I only want to run 2. How can I achieve this programmatically/dynamically (not from the command line, Eclipse etc.).
Also, there is the case where there is a @Before
annotated method in the test class. So, when running an individual test method, the @Before
should run beforehand as well. How can that be overcome?
Thanks in advance.
回答1:
This is a simple single method runner. It's based on JUnit 4 framework but can run any method, not necessarily annotated with @Test
private Result runTest(final Class<?> testClazz, final String methodName)
throws InitializationError {
BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(testClazz) {
@Override
protected List<FrameworkMethod> computeTestMethods() {
try {
Method method = testClazz.getMethod(methodName);
return Arrays.asList(new FrameworkMethod(method));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
Result res = new Result();
runner.run(res);
return res;
}
class Result extends RunNotifier {
Failure failure;
@Override
public void fireTestFailure(Failure failure) {
this.failure = failure;
};
boolean isOK() {
return failure == null;
}
public Failure getFailure() {
return failure;
}
}
回答2:
I think this can only be done with a custom TestRunner. You could pass the names of the tests you wish to run as arguments when launching your tests. A more fancier solution would be to implement a custom annotation (lets say @TestGroup), which takes a group name as argument. You could than annotate your test methods with it, giving those tests you want to run together the same group name. Again, pass the group name as argument when launching the tests. Within your test runner, collect only those methods with the corresponding group name and launch those tests.
However, the simplest solution to this is to move those tests you want to run separately to another file...
来源:https://stackoverflow.com/questions/13605774/how-to-run-a-single-method-in-a-junit-4-test-class