TestInfoParameterResolver

Given a test class, if a method parameter is of type TestInfo, the JUnit 5 resolver TestInfoParameterResolver supplies an instance of TestInfo corresponding to the current test as the value for the declared parameter. The TestInfo object is used to retrieve information about the current test, such as the test display name, the test class, the test method, or associated tags.

TestInfo acts as a drop-in replacement for the TestName rule from JUnit 4.

The class TestInfo is placed in the package org.junit.jupiter.api and offers the following API:

  • String getDisplayName() : This returns the display name of the test or container.
  • Set<String> getTags() : This gets the set of all tags for the current test or container.
  • Optional<Class<?>> getTestClass() : This gets the class associated with the current test or container, if available.
  • Optional<Method> getTestMethod() : This gets the method associated with the current test, if available.
TestInfo API

Let's see an example. Notice that in the following class, both the methods annotated with @BeforeEach and @Test accepts a parameter of TestInfo. This parameter is injected by TestInfoParameterResolver:

package io.github.bonigarcia;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;

class TestInfoTest {

@BeforeEach
void init(TestInfo testInfo) {
String displayName = testInfo.getDisplayName();
System.out.printf("@BeforeEach %s %n", displayName);
}

@Test
@DisplayName("My test")
@Tag("my-tag")
void testOne(TestInfo testInfo) {
System.out.println(testInfo.getDisplayName());
System.out.println(testInfo.getTags());
System.out.println(testInfo.getTestClass());
System.out.println(testInfo.getTestMethod());
}

@Test
void testTwo() {
}

}

Therefore, in the body of each method, we are able to use the TestInfo API to get the test information at runtime, as the following screenshot demonstrates:

Console output of dependency injection of TestInfo objects
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.74.211