问题描述
测试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());
}
}
运行测试时,它总是经过拦截器并被拒绝,因为我没有有效的令牌。我的代码经过简化,无法获得有效的令牌进行测试,因此我确实需要跳过拦截器。
感谢您的帮助
解决方法
要模拟它(在集成测试中):
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
// non-static imports
@SpringBootTest
// other stuff
class IntegrationTest {
@MockBean
RequestInterceptor interceptor;
// other stuff
@BeforeEach
void initTest() {
when(interceptor.preHandle(any(),any(),any())).thenReturn(true);
// other stuff
}
// tests
}
你知道@BeforeEach和@SpringBootTest做什么? Mockito的any()只是说“不管参数如何”;对于@MockBean和Mockito的when-then,Javadoc足够好,我觉得不需要添加信息。
,我可以通过使用拦截器上的配置文件来解决此问题。在测试中,您不使用配置文件运行(未注入bean)。在您的生产或需要的环境中,都可以使用新的配置文件运行。
当然,您需要稍微更改用法。这应该起作用:
@Configuration
public class RequestInterceptorAppConfig implements WebMvcConfigurer {
@Autowired
Collection<RequestInterceptor> requestInterceptors;
@Override
public void addInterceptors(InterceptorRegistry registry) {
requestInterceptors.forEach(interceptor -> registry.addInterceptor(interceptor).addPathPatterns("/**");
}
}