Get name of currently executing test in JUnit 4
JUnit 4.7 added this feature it seems using TestName-Rule. Looks like this will get you the method name:
import org.junit.Rule;
public class NameRuleTest {
@Rule public TestName name = new TestName();
@Test public void testA() {
assertEquals("testA", name.getMethodName());
}
@Test public void testB() {
assertEquals("testB", name.getMethodName());
}
}
Get currently executing @Test method in @Before in JUnit 4
try TestName rule
public class TestCaseExample {
@Rule
public TestName testName = new TestName();
@Before
public void setUp() {
Method m = TestCaseExample.class.getMethod(testName.getMethodName());
...
}
...
JUnit 4: how to get test name inside a Rule?
If you just need a @Rule
with the test name, don't reinvet the wheel, just use the built-in TestName
@Rule
.
If you're trying to build your own rule that adds some logic to it, consider extending it. If that isn't an option either, you could just copy it's implementation.
To answer the question in the comment, like any other TestRule
, ExternalResouce
also has an apply(Statement, Description)
method. You can add functionality to it by overriding it, just make sure you call the super method so you don't break the ExternalResource
functionality:
public class MyRule extends ExternalResource {
private String testName;
@Override
public Statement apply(Statement base, Description description) {
// Store the test name
testName = description.getMethodName();
return super.apply(base, description);
}
public void before() {
// Use it in the before method
System.out.println("Test name is " + testName);
}
}
How to obtain test case name in JUnit 4 at runtime?
OK. I've found another approach [somewhere on the Internet](http://www.nabble.com/What-happened-to-getName()--td23456371.html):
@RunWith(Interceptors.class)
public class NameTest {
@Interceptor public TestName name = new TestName();
@Test public void funnyName() {
assertEquals("funnyName", name.getMethodName());
}
}
junit 4.10: how to get the name of the tests class while running tests
Just use
this.getClass().getName()
or
this.getClass().getSimpleName()
Depending if you want the full name with package or just the simple class name.
Related Topics
The Difference Between the Runnable and Callable Interfaces in Java
Most Efficient Way to Increment a Map Value in Java
Difference Between Jar and War in Java
Subclassing a Java Builder Class
Can Constructors Throw Exceptions in Java
Quickest Way to Find Missing Number in an Array of Numbers
How to Define a List Bean in Spring
Does a Tcp Socket Connection Have a "Keep Alive"
Converting Many 'If Else' Statements to a Cleaner Approach
Finding Key Associated with Max Value in a Java Map
How to Create Executable Java Program
Java 8's Streams: Why Parallel Stream Is Slower