How to test Spring Aspects

Oct 13, 2021 | - views

Project structure

@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

@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);
  }
}