首页 > 解决方案 > 在模拟 HandlerInterceptorAdapter 的情况下,不会为 prehandle() 调用模拟行为

问题描述

    public class MyInteceptor extends HandlerInterceptorAdapter {
        @Override
        public final boolean preHandle(HttpServletRequest request, final HttpServletResponse response, 
         final Object handler) {
            System.out.println("Logging token interceptor");
            return true;
        }
    }


@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
public class MyTest {
  @MockBean
  private MyInterceptor myInterceptor;
  
  @Test
  public void shouldTestPostRequest() throws Exception {
    
    when(myInterceptor.preHandle(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Object.class))).thenReturn(true);
    


    mockMvc.perform(post("/v1/myApi")
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(request))) // valid request DTO is present
            .andExpect(status().isCreated())
            .andReturn();
}

当 mockMvc 调用 POST 方法时,模拟的“myInterceptor”出现在上下文中,但不会调用在 prehandle() 上添加的模拟行为,并且会调用实际拦截器的 prehandle()。

标签: spring-bootmockitospring-boot-testmockmvc

解决方案


推荐阅读