|
1
|
|
|
package io.github.glytching.junit.extension.testname; |
|
2
|
|
|
|
|
3
|
|
|
import org.junit.jupiter.api.extension.AfterTestExecutionCallback; |
|
4
|
|
|
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; |
|
5
|
|
|
import org.junit.jupiter.api.extension.ExtensionContext; |
|
6
|
|
|
|
|
7
|
|
|
import java.lang.reflect.Field; |
|
8
|
|
|
import java.util.Optional; |
|
9
|
|
|
|
|
10
|
|
|
import static org.junit.platform.commons.support.AnnotationSupport.isAnnotated; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* The test name extension makes the current test name available inside each test method. |
|
14
|
|
|
* |
|
15
|
|
|
* <p>Usage example: |
|
16
|
|
|
* |
|
17
|
|
|
* <p>Injecting random values as fields: |
|
18
|
|
|
* |
|
19
|
|
|
* <pre> |
|
20
|
|
|
* @ExtendWith(TestNameExtension.class) |
|
21
|
|
|
* public class MyTest { |
|
22
|
|
|
* |
|
23
|
|
|
* @TestName |
|
24
|
|
|
* private String testName; |
|
25
|
|
|
* |
|
26
|
|
|
* @Test |
|
27
|
|
|
* public void testUsingRandomString() { |
|
28
|
|
|
* // use the populated testName |
|
29
|
|
|
* // ... |
|
30
|
|
|
* } |
|
31
|
|
|
* } |
|
32
|
|
|
* </pre> |
|
33
|
|
|
* |
|
34
|
|
|
* @since 1.1.0 |
|
35
|
|
|
*/ |
|
36
|
|
|
public class TestNameExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback { |
|
37
|
|
|
|
|
38
|
|
|
@Override |
|
39
|
|
|
public void beforeTestExecution(ExtensionContext extensionContext) throws Exception { |
|
40
|
|
|
setTestNameFieldValue( |
|
41
|
|
|
getTestNameField(extensionContext), |
|
42
|
|
|
extensionContext.getRequiredTestInstance(), |
|
43
|
|
|
extensionContext.getRequiredTestMethod().getName()); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
@Override |
|
47
|
|
|
public void afterTestExecution(ExtensionContext extensionContext) throws Exception { |
|
48
|
|
|
setTestNameFieldValue( |
|
49
|
|
|
getTestNameField(extensionContext), extensionContext.getRequiredTestInstance(), null); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
private Optional<Field> getTestNameField(ExtensionContext extensionContext) { |
|
53
|
|
|
for (Field field : extensionContext.getRequiredTestClass().getDeclaredFields()) { |
|
54
|
|
|
if (isAnnotated(field, TestName.class)) { |
|
55
|
|
|
return Optional.of(field); |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
return Optional.empty(); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") |
|
62
|
|
|
private void setTestNameFieldValue( |
|
63
|
|
|
Optional<Field> testNameField, Object testInstance, String value) throws IllegalAccessException { |
|
64
|
|
|
if (testNameField.isPresent()) { |
|
65
|
|
|
testNameField.get().setAccessible(true); |
|
66
|
|
|
testNameField.get().set(testInstance, value); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|