@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(SearchController.class)
@ContextConfiguration(classes = SearchControllerTest.SearchControllerTestConfiguration.class)
public class SearchControllerTest {
private static final String TEST_STRING = "test";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Autowired private SearchService searchService;
@Autowired private MockMvc mockMvc;
@Before public void setup() {
final SearchController searchController = new SearchController(searchService);
this.mockMvc = MockMvcBuilders.standaloneSetup(searchController)
.setHandlerExceptionResolvers(getHandlerExceptionResolver())
.build();
}
@Test
public void givenOKResponse_whenValidRequest() throws Exception {
final ApiRequestHeader header = getApiRequestHeader();
final ApiRequest<SuggestRequest> apiRequest = getApiRequest(header, TEST_STRING, Collections.singletonList(TEST_STRING));
ObjectWriter ow = OBJECT_MAPPER.writer();
String requestJson = ow.writeValueAsString(apiRequest);
given(searchService.suggest(Mockito.any(SuggestRequest.class))).willReturn(buildSuggestResponse());
final MvcResult mvcResult = mockMvc.perform(post("/v1/suggest")
.contentType(APPLICATION_JSON_VALUE)
.content(requestJson))
.andReturn();
mockMvc
.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(header().string(CONTENT_TYPE, APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("ResponseHeader.responseCode").value(200))
.andExpect(jsonPath("ResponseBody.variants").value(TEST_STRING));
}
private HandlerExceptionResolver getHandlerExceptionResolver() {
final StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("exceptionHandler", RestExceptionHandler.class);
final WebMvcConfigurationSupport webMvcConfigurationSupport = new WebMvcConfigurationSupport();
webMvcConfigurationSupport.setApplicationContext(applicationContext);
return webMvcConfigurationSupport.handlerExceptionResolver();
}
private ApiRequest<SuggestRequest> getApiRequest(ApiRequestHeader header, String query, List list) {
}
private ApiRequestHeader getApiRequestHeader() {
}
private CompletableFuture<ApiResponse<SuggestResponseData>> buildSuggestResponse() { }
@Configuration public static class SearchControllerTestConfiguration {
@Autowired private WebApplicationContext wac;
@Bean
public MockMvc mockMvc() {
return MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Bean
public SearchService searchService() {
return Mockito.mock(SearchService.class);
}
}
}