简体   繁体   中英

What is the equivalent of TestName rule in JUnit 5?

How can I get name of the test method in JUnit 5?

Declare a parameter of type TestInfo in your test method and JUnit will automatically supply an instance of that for the method:

@Test
void getTestInfo(TestInfo testInfo) { // Automatically injected
    System.out.println(testInfo.getDisplayName());
    System.out.println(testInfo.getTestMethod());
    System.out.println(testInfo.getTestClass());
    System.out.println(testInfo.getTags());
}

You can get test method name (and more) from the TestInfo instance as shown above.

In addition to what is written about injecting TestInfo to test method it is also possible to inject TestInfo to methods annotated with @BeforeEach and @AfterEach which might be useful sometimes:

@BeforeEach
void setUp(TestInfo testInfo) {
  log.info(String.format("test started: %s", testInfo.getDisplayName());
}
@AfterEach
void tearDown(TestInfo testInfo) {
  log.info(String.format("test finished: %s", testInfo.getDisplayName());
}

An alternative for having the test name globally available as was possible in JUnit 4 is to shim the functionality yourself in a setup method using the TestInfo interface.

From the JUnit documentation on "Dependency Injection for Constructors and Methods" :

The TestInfo can then be used to retrieve information about the current container or test such as the display name, the test class, the test method, and associated tags.

Here we leverage the fact that the built-in resolvers will supply an instance of TestInfo corresponding to the current container or test as the value for parameters of type TestInfo to methods annotated as lifecycle hooks (here we use @BeforeEach ).

import org.junit.jupiter.api.TestInfo;

public class MyTestClass {
  String displayName;

  @BeforeEach
  void setUp(TestInfo testInfo) {
    displayName = testInfo.getDisplayName();
    // ... the rest of your setup
  }
}

This for example enables you to reference the current test name in other non-test methods (such as various utility methods) without having to include the test name as a parameter to each function call from the initial test method to that utility method.

You can do the same for other information about the current container or test.

Seems like the only disadvantages are:

  • the instance variable cannot be made final , as it is set dynamically
  • may pollute your setup code

For reference, here is how the TestName-Rule might be implemented in JUnit 4:

public class MyTestClass {
  @Rule
  public final TestName name = new TestName();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM