1

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?
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
eastwater
  • 4,624
  • 9
  • 49
  • 118

1 Answers1

2

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);
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • MyRule needs to extends ExternalResource because its contains Before() and After(). But it does not have starting(Description d) method. How to get method name inside MyRule? thanks. – eastwater Jan 04 '20 at 08:30