我想对spring boot rest-api应用程序进行一些端到端测试。为了达到这个目的,我使用了Spring Mock MVC。但是我无法获得200响应,因为其余api使用自定义安全拦截器来验证请求中的令牌。相反,我一直收到401作为回应。如何在我的测试中包含此令牌验证?
我通过在测试类中包含@ContextConfiguration(classes = {WebMvcConfig.class})尝试了几种配置。 WebMvcConfig是用于配置拦截器的配置类。
这是我的测试文件
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
@SpringBootTest(classes = VeripalServiceApplication.class)
@TestPropertySource(locations="classpath:test.properties")
@Transactional
public class VeripalTextConfigurationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void happpyPath_thenReturns200() throws Exception {
String jsonBody = "some json body";
String endPoint = "/end_point_to_my_api";
HttpHeaders headers = new HttpHeaders();
headers.add("token", "this_is_my_token");
headers.setContentType(aplication/json);
/** Hit the API */
mockMvc.perform(post(endPoint)
.headers(httpHeaders)
.content(jsonBody)
)
.andExpect(status().isOk()).andDo(print());
}
}
这是@Configuration
@Configuration
@EnableScheduling
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
private ConsumerService consumerService;
@Autowired
private EndpointService endpointService;
@Autowired
private ConsumerConfigurationService consumerConfigurationService;
@Autowired
private AccessLimitService accessLimitService;
@Autowired
private ConfigurationHistoryService configurationHistoryService;
@Autowired
private LimitCarryOverService limitCarryOverService;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new Interceptor(consumerService, endpointService, consumerConfigurationService, accessLimitService, configurationHistoryService, limitCarryOverService));
}
}
这是我的拦截器课程
public class Interceptor implements HandlerInterceptor {
// some code here ...
}
答案 0 :(得分:0)
您需要清楚地了解Servlet API和Spring Security框架中的请求生命周期。
本文可能会帮助您了解此流程http://blog.florian-hopf.de/2017/08/spring-security.html
因此,我敢肯定,您在身份验证过滤器中存在问题,因此可以通过以下几种方式解决此问题:
。
相关帖子:
V2:使用IoC + Mockito,例如存根进行单元测试。我看不到您的代码是如何编写的,因此,我相信下面的代码片段可能会对您有所帮助。
// @Import({MyAuthCustomInterceptor.class}) // eq to @Component/@Service to create a bean
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
MyAuthCustomInterceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor);
}
}
public class VeripalTextConfigurationTest {
@MockBean
MyAuthCustomInterceptor interceptor;
@SetUp
public void setup(){
Mockito.when(interceptor.preHandle(...)).thenReturn(true);
}
}