io.github.glytching.junit.extension.testname.TestNameExtension Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of junit-extensions Show documentation
Show all versions of junit-extensions Show documentation
JUnit Jupiter extensions, providing 'JUnit5 replacements' for some common JUnit4 Rules.
package io.github.glytching.junit.extension.testname;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import java.lang.reflect.Field;
import java.util.Optional;
import static org.junit.platform.commons.support.AnnotationSupport.isAnnotated;
/**
* The test name extension makes the current test name available inside each test method.
*
* Usage example:
*
*
Injecting random values as fields:
*
*
* @ExtendWith(TestNameExtension.class)
* public class MyTest {
*
* @TestName
* private String testName;
*
* @Test
* public void testUsingRandomString() {
* // use the populated testName
* // ...
* }
* }
*
*
* @since 1.1.0
*/
public class TestNameExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
@Override
public void beforeTestExecution(ExtensionContext extensionContext) throws Exception {
setTestNameFieldValue(
getTestNameField(extensionContext),
extensionContext.getRequiredTestInstance(),
extensionContext.getRequiredTestMethod().getName());
}
@Override
public void afterTestExecution(ExtensionContext extensionContext) throws Exception {
setTestNameFieldValue(
getTestNameField(extensionContext), extensionContext.getRequiredTestInstance(), null);
}
private Optional getTestNameField(ExtensionContext extensionContext) {
for (Field field : extensionContext.getRequiredTestClass().getDeclaredFields()) {
if (isAnnotated(field, TestName.class)) {
return Optional.of(field);
}
}
return Optional.empty();
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private void setTestNameFieldValue(
Optional testNameField, Object testInstance, String value) throws Exception {
if (testNameField.isPresent()) {
testNameField.get().setAccessible(true);
testNameField.get().set(testInstance, value);
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy