GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

beforeTestExecution(ExtensionContext)   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 6
rs 10
eloc 6
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
 * &#064;ExtendWith(TestNameExtension.class)
21
 * public class MyTest {
22
 *
23
 *     &#064;TestName
24
 *     private String testName;
25
 *
26
 *     &#064;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