In JUnit 3, I could get the name of the currently running test like this:
public class MyTest extends TestCase
{
public void testSomething()
{
System.out.println("Current test is " + getName());
...
}
}
which would print "Current test is testSomething".
Is there any out-of-the-box or simple way to do this in JUnit 4?
Background: Obviously, I don't want to just print the name of the test. I want to load test-specific data that is stored in a resource with the same name as the test. You know, convention over configuration and all that.
JUnit 4 does not have any out-of-the-box mechanism for a test case to get it’s own name (including during setup and teardown).
In JUnit 5 there is
TestInfo
injection which simplifies test meta data providing to test methods. For example:See more: JUnit 5 User guide, TestInfo javadoc.
In JUnit 5
TestInfo
acts as a drop-in replacement for the TestName rule from JUnit 4.From the documentation :
To retrieve the method name of the current executed test, you have two options :
String TestInfo.getDisplayName()
andMethod TestInfo.getTestMethod()
.To retrieve only the name of the current test method
TestInfo.getDisplayName()
may not be enough as the test method default display name ismethodName(TypeArg1, TypeArg2, ... TypeArg3)
.Duplicating method names in
@DisplayName("..")
is not necessary a good idea.As alternative you could use
TestInfo.getTestMethod()
that returns aOptional<Method>
object.If the retrieval method is used inside a test method, you don't even need to test the
Optional
wrapped value.A convoluted way is to create your own Runner by subclassing org.junit.runners.BlockJUnit4ClassRunner.
You can then do something like this:
Then for each test class, you'll need to add a @RunWith(NameAwareRunner.class) annotation. Alternatively, you could put that annotation on a Test superclass if you don't want to remember it every time. This, of course, limits your selection of runners but that may be acceptable.
Also, it may take a little bit of kung fu to get the current test name out of the Runner and into your framework, but this at least gets you the name.
Consider using SLF4J (Simple Logging Facade for Java) provides some neat improvements using parameterized messages. Combining SLF4J with JUnit 4 rule implementations can provide more efficient test class logging techniques.