我在测试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());
}
}
在运行测试时,由于没有有效的令牌,它始终通过拦截器并被拒绝。我的代码已经被简化,无法获得有效的令牌进行测试,因此我真的需要跳过拦截器。
谢谢您的帮助。