|
Re: How to get test's name in JUnit 4
> > It seems like the RunListeneer would have a reference to the currently
> > running test, simply because of its "testStarted" and "testFinished"
> > functions
[...]
> > Is it possible to get access to this from within the test class
> > itself?
>
> No, by design. Sorry about that.
[...]
> Information on custom runners is currently somewhat lacking. It
> appears from your later message that you've somewhat successfully
> navigating the waters. Any interest in writing up a short blog entry
> or article on your experiences? Thanks,
>
> David Saff
>
To get a test's name use this runner with the
@RunWith(NameAwareTestClassRunner.class) at the top of your test class
and inside your @Before method do something like:
String testName = NameAwareTestClassRunner.getTestName();
Anyway, here's the runner.
// NameAwareTestClassRunner.java
import org.junit.internal.runners.InitializationError;
import org.junit.internal.runners.TestClassRunner;
import org.junit.runner.Description;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
public class NameAwareTestClassRunner extends TestClassRunner {
public NameAwareTestClassRunner(Class<?> klass) throws
InitializationError {
super(klass);
}
private static String testName;
protected static String getName() {
return testName;
}
protected static void setName(final String name) {
testName = name;
}
protected static String getTestName() {
if (testName == null)
return null;
int last = testName.indexOf('(');
if (last < 0)
last = testName.length() + 1;
return testName.substring(0, last);
}
private static class NameListener extends RunListener {
/** Record start of tests, not suites */
public void testStarted(Description description) throws Exception {
System.err.println(" STARTED: " + description.getDisplayName());
setName(description.isTest() ? description.getDisplayName() : null);
}
public void testFinished(Description description) throws Exception {
System.err.println("FINISHED: " + description.getDisplayName());
if (getName() != null)
if (getName().equals(description.getDisplayName()))
setName(null);
else
throw new Exception("Test name mismatch");
}
}
public void run(final RunNotifier notifier) {
notifier.addListener(new NameListener());
super.run(notifier);
}
}
|