0

I am trying to write the integration test for my controller.

Exception handler is there in a library as part of dependency. But my webMvc Test is not able to invoke the handler

The exception is thrown from method

@WebMvcTest(controllers = MyController.class, excludeAutoConfiguration = {
    SecurityAutoConfiguration.class})
@ExtendWith(SpringExtension.class)
public class WebMockTest {

  @Autowired
  private MockMvc mockMvc;

  @MockBean
  private MyService service;

  
  @Test
  public void shall_make_get_call_404_not_ok() throws Exception {
    when(service.getById(any())).thenThrow(new CustomException("Not found"));
    this.mockMvc.perform(get("/items/" + "12")).andDo(print())
        .andExpect(status().isNotFound());

  }
}

Here I am not able to get the response but exception is thrown from test method.

How do I trigger the exception handler.

Patan
  • 17,073
  • 36
  • 124
  • 198

1 Answers1

0

You need to add @Import(Exceptionhandler.class).

I described a similar problem, when using @WebMvcTest with specific controllers and its solution here: https://stackoverflow.com/a/74191408/7789681

Alexey Bril
  • 479
  • 4
  • 14