Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Aspectj test with MockMvc

I have a Spring boot code with Aspectj. This code has written with basic MVC architecture. Then I just try to test it with MockMVC. But when I try to test it, Aspectj doesn't interrupted. Is there a special configuration about Aspectj?

Controller:

@GetMapping("user/{userId}/todo-list")
public ResponseEntity<?> getWaitingItems(@RequestUser CurrentUser currentUser){
    ...handle it with service method.
}

Aspect:

@Pointcut("execution(* *(.., @RequestUser (*), ..))")
void annotatedMethod()
{
}

@Before("annotatedMethod() && @annotation(requestUser)")
public void adviseAnnotatedMethods(JoinPoint joinPoint, RequestUser requestUser)
{
    ...
}

Test:

@WebMvcTest(value = {Controller.class, Aspect.class})
@ActiveProfiles("test")
@ContextConfiguration(classes = {Controller.class, Aspect.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class ControllerTest
{
    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private Controller controller;

    @MockBean
    private Service service;

    @Before
    public void setUp()
    {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .build();
    }

    @Test
    public void getWaitingItems() throws Exception
    {
        mockMvc.perform(get("/user/{userId}/todo-list", 1L))
                .andExpect(status().isOk());
    }
}
like image 982
Sha Avatar asked Jan 25 '23 08:01

Sha


1 Answers

There is no need for a @SpringBootTest if you wanna do integration tests of specific controller (web layer) + your custom Aspect logic (AOP layer).

Try something like this

@WebMvcTest(controllers = {AnyController.class})
@Import({AopAutoConfiguration.class, ExceptionAspect.class})
public class ErrorControllerAdviceTest {
  • AnyController.class: controller under test
  • AopAutoConfiguration.class: Spring Boot auto-configuration of AOP
  • ExceptionAspect.class: class containing AOP logic
@Aspect
@Component
public class ExceptionAspect {}

Tested with Spring Boot 2.2.1.RELEASE and JUNIT5. I am unsure, if my solution is technically the same like @Deadpool answers

like image 77
rfelgent Avatar answered Jan 30 '23 04:01

rfelgent