Search code examples
javajunitjunit4junit-rule

JUnit 4: how to get test name inside a Rule?


JUnit 4: how to get test name inside a Rule? e.g.,

public class MyRule extends ExternalResource {

    @Before
    public void before() {
        // how to get the test method name to be run?
    }
}

Solution

  • 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);
        }
    }