我正在使用 spring-boot 3.4.2。
我想使用 AOP 方面来修改我在 Spring Boot 测试中使用的注释。
但是我的 @Around 方法在测试执行期间不会被触发。如果我注释 Rest 控制器内的端点方法,则会触发该方法。但我想使用它进行测试。
这是我的注释:
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
}
以下是我的观点:
@Aspect
@Component
public class TestAspect {
public TestAspect() {
// this is called - so @Component works
System.out.println("aspect constructor called");
}
@Around("@annotation(TestAnnotation)")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
// this is NOT called in the test - @Around did not work
System.out.println("aroundAdvice() called");
return joinPoint.proceed();
}
}
这是我的测试:
@SpringBootTest
@ComponentScan(basePackages = { "de.mycompany" }) // root of all my packages
@TestPropertySource(value = "classpath:application-test.yml", factory = YamlPropertySourceFactory.class)
@AutoConfigureMockMvc
class MyTestClass {
@Autowired
private MockMvc mockMvc;
@Test
@TestAnnotation
void testSomething() throws Exception {
System.out.println("testSomething() called.");
// test something with mockMvc
}
}
如果我在 RestController 中注释了一个端点,aroundAdvice()
则每当调用或测试该端点时都会触发它。但我需要在调用我的测试方法(此处:)时触发它testSomething()
。但这行不通。
使用完全限定的类@Around
也不起作用:
@Around("@annotation(de.mycompany.annotation.TestAnnotation)")