spring-boot - 在模拟 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()。
解决方案
推荐阅读
- docker - Filecoin Textileio Powergate 没有足够的矿工来自声誉模块来满足约束错误
- github - GitHub 归档过时的文件
- java - 在单例中使用同步块
- arrays - 特定索引 mongodb 上的数组到数组连接
- azure - Azure Datalake Storage 列出容器中的第一级目录
- javascript - 未在 ui 中呈现的数据在使用 useEffect 做出反应
- javascript - Fetch 数据已加载到 DOM 上,但无法选择
- python - 如何在 Ubuntu 中更新 Docx 文件中的目录
- kubernetes - 如何恢复牧场主集群
- elasticsearch - 如何在Django Elastic query dsl中匹配搜索词中的冒号