【发布时间】:2020-09-11 13:20:17
【问题描述】:
我在测试 REST 请求时遇到问题。在我的应用程序中,我有一个拦截器,可以在允许请求之前检查令牌的有效性。但是对于我的集成测试,我想绕过检查。换句话说,我想分流拦截器或模拟它以始终返回 true。
这是我的简化代码:
@Component
public class RequestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String token = request.getHeader("Authorization");
if (token != null) {
return true;
} else {
return false;
}
}
}
@Configuration
public class RequestInterceptorAppConfig implements WebMvcConfigurer {
@Autowired
RequestInterceptor requestInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(requestInterceptor).addPathPatterns("/**");
}
}
和测试:
@SpringBootTest(classes = AppjhipsterApp.class)
@AutoConfigureMockMvc
@WithMockUser
public class DocumentResourceIT {
@Autowired
private DocumentRepository documentRepository;
@Autowired
private MockMvc restDocumentMockMvc;
private Document document;
public static Document createEntity() {
Document document = new Document()
.nom(DEFAULT_NOM)
.emplacement(DEFAULT_EMPLACEMENT)
.typeDocument(DEFAULT_TYPE_DOCUMENT);
return document;
}
@BeforeEach
public void initTest() {
document = createEntity();
}
@Test
@Transactional
public void createDocument() throws Exception {
int databaseSizeBeforeCreate = documentRepository.findAll().size();
// Create the Document
restDocumentMockMvc.perform(post("/api/documents")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(document)))
.andExpect(status().isCreated());
}
}
运行测试时,它总是通过拦截器并被拒绝,因为我没有有效的令牌。我这里的代码被简化了,我无法获得有效的测试令牌,所以我真的需要跳过拦截器。
感谢您的帮助
【问题讨论】:
标签: java spring spring-boot integration-testing interceptor