I want to do some end-to-end test for spring boot rest-api application. To achieve this im using spring mock mvc. But i can't get the 200 response because the rest api is using custom security interceptor to validate the token in request. Instead i keep getting 401 as a response. How to include this token validation in my test?
I've tried several configuration by including @ContextConfiguration(classes = {WebMvcConfig.class}) in my test class. WebMvcConfig is configuration class to register the interceptor.
This is my test file
@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());
}
}
And this is the @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));
}
}
And this is my Interceptor class
public class Interceptor implements HandlerInterceptor {
// some code here ...
}