Project structure
- Annotation marker
AopMarker
- Aspect
AopMarkerAspect
that handle AopMarker
- Service
MyService
injected to AopMarkerAspect
and triggered every time when aspect
handled.
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface AopMarker {
}
@Aspect
@Component
public class AopMarkerAspect {
@Autowired
MyService myService;
@Around("@annotation(name.mrkandreev.aspecttest.annotation.AopMarker)")
public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
myService.invoke(method);
return joinPoint.proceed();
}
}
public interface MyService {
void invoke(Method method);
}
Test structure
- Test
AopMarkerAspectTest
with @EnableAspectJAutoProxy
AopInjectedService
annotated with @AopMarker
@TestConfiguration
with mocked MyService
service
- Single
test()
case in AopMarkerAspectTest
that invoke
AopInjectedService
and expect that myService
was invoked.
@ExtendWith(SpringExtension.class)
@EnableAspectJAutoProxy
@Import({AopMarkerAspectTestConfiguration.class, AopMarkerAspect.class, AopInjectedService.class})
class AopMarkerAspectTest {
@Autowired
MyService myService;
@Autowired
AopInjectedService aopInjectedService;
@Test
void test() {
aopInjectedService.invoke();
verify(myService, times(1)).invoke(any());
}
}
@Component
class AopInjectedService {
@AopMarker
public void invoke() {
// empty
}
}
@TestConfiguration
class AopMarkerAspectTestConfiguration {
@Bean
public MyService myService() {
return Mockito.mock(MyService.class);
}
}