Search code examples
spring-bootmockitojunit5spring-aopspringmockito

How to mock a method of Aspect class?


I have added a custom annotation on a method which is present inside a controller class. I have implemented Aspect class which is considering custom annotation as a point-cut. Once the execution reaches to custom annotation ,it calls the interceptor method which is present inside the class .This interceptor method contains a logic which calls the database to save the data.

While writing testcases for controller class, how can I mock above mentioned interceptor method so that I can resist the database call ?

Note: Inside interceptor method I am calling a method of another class which is the implementation of HandlerInterceptor

@Aspect
class SampleAspect {
  @Around("execution(@Xyz)")
  public Object interceptor(ProceedingJoinPoint jointPoint) {
    // database logic
  }
}
@RestController 
class SampleController {
  @GetMapping("/{id}")
  @Xyz
  public String getdata(String id) {
    return "hello";
  }
}

Solution

  • I wrote two answers which might be of interest to you:

    Please start from there and let me know if you have any follow-up problems, updating your own question and showing exactly what you are trying to do.