Skip to content

Commit

Permalink
Use ReflectionTestUtils for invoking @DynamicPropertySource methods
Browse files Browse the repository at this point in the history
  • Loading branch information
nosan committed Oct 28, 2024
1 parent a68a884 commit 008de18
Showing 1 changed file with 4 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import org.springframework.javapoet.CodeBlock;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
Expand Down Expand Up @@ -201,7 +202,6 @@ private static GeneratedMethod generateMethod(GenerationContext generationContex
code.addModifiers(javax.lang.model.element.Modifier.PRIVATE,
javax.lang.model.element.Modifier.STATIC);
code.addParameter(DynamicPropertyRegistry.class, DYNAMIC_PROPERTY_REGISTRY);

if (isMethodAccessible(generatedClass, method)) {
code.addStatement(CodeBlock.of("$T.$L($L)", method.getDeclaringClass(), method.getName(),
DYNAMIC_PROPERTY_REGISTRY));
Expand All @@ -211,12 +211,9 @@ private static GeneratedMethod generateMethod(GenerationContext generationContex
code.beginControlFlow("try");
code.addStatement("$T<?> clazz = $T.forName($S, $T.class.getClassLoader())", Class.class,
ClassUtils.class, ClassName.get(method.getDeclaringClass()), generatedClass.getName());
code.addStatement("$T method = $T.findMethod(clazz, $S, $T.class)", Method.class,
ReflectionUtils.class, method.getName(), DynamicPropertyRegistry.class);
code.addStatement("$T.notNull(method, $S)", Assert.class,
"Method '" + method.getName() + "' is not found");
code.addStatement("$T.makeAccessible(method)", ReflectionUtils.class);
code.addStatement("$T.invokeMethod(method, null, $L)", ReflectionUtils.class,
// ReflectionTestUtils can be used here because
// @DynamicPropertyRegistry in a test module.
code.addStatement("$T.invokeMethod(clazz, $S, $L)", ReflectionTestUtils.class, method.getName(),
DYNAMIC_PROPERTY_REGISTRY);
code.nextControlFlow("catch ($T ex)", ClassNotFoundException.class);
code.addStatement("throw new $T(ex)", RuntimeException.class);
Expand Down

0 comments on commit 008de18

Please sign in to comment.