Tim*_*age 5 java spring integration-testing interceptor spring-boot
我在测试 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("/**");
}
}
Run Code Online (Sandbox Code Playgroud)
和测试:
@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());
}
}
Run Code Online (Sandbox Code Playgroud)
运行测试时,它总是通过拦截器并被拒绝,因为我没有有效的令牌。我这里的代码被简化了,我无法获得有效的令牌进行测试,所以我真的需要跳过拦截器。
感谢您的帮助
模拟它(在集成测试中):
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
}
Run Code Online (Sandbox Code Playgroud)
@BeforeEach 和 @SpringBootTest 做什么,你知道;Mockito 的 any() 只是说“无论参数如何”;对于 @MockBean 和 Mockito 的何时-那么,Javadoc 已经足够好了,我觉得不需要添加信息。
| 归档时间: |
|
| 查看次数: |
5267 次 |
| 最近记录: |