Register @ControllerAdvice annotated Controller in JUnitTest with MockMVC

后端 未结 5 2063
孤街浪徒
孤街浪徒 2021-01-01 10:10

My @ControllerAdvice annotated Controller looks like this:

@ControllerAdvice
public class GlobalControllerExceptionHandler {

    @ResponseStatu         


        
5条回答
  •  盖世英雄少女心
    2021-01-01 11:10

    You can add this to your test class

    @Autowired
    @Qualifier("handlerExceptionResolver")
    void setExceptionResolver(HandlerExceptionResolver resolver)
    {
        this.exceptionResolver = resolver;
    }
    

    and then add the exceptionResolver to your MockMvc

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller)
                   .setHandlerExceptionResolvers(this.exceptionResolver).build();
    }
    

提交回复
热议问题