class FooApiServiceTest extends SpringRunnerSupport {
private static final String API_URL = "http://www.freeism.co.kr/api/v1/test";
private static final String ID = "FREEISM";
@Autowired
private FooApiService dut;
@Autowired
private RestTemplate restTemplate;
private MockRestServiceServer server;
@BeforeEach
void before() {
server = MockRestServiceServer.createServer(restTemplate);
}
@Test
void whenSuccess() throws Exception {
givenSucessApiResponse();
FooResponse result = dut.request(ID);
assertThat(result.get(), is("SUCCESS"));
assertThat(result.getId(), is(ID));
}
@Test
void whenFailure() throws Exception {
givenFailureApiResponse();
FooResponse result = dut.request(ID);
assertThat(result.getStatus(), not("SUCCESS"));
}
@Test
void whenError() throws Exception {
givenErrorApiResponse();
FooResponse result = dut.request(CID);
assertThat(result, is(FooResponse.emptyObject()));
}
private void givenSucessApiResponse() throws Exception {
givenApiResponse(HttpStatus.OK, asJson(mockSuccessResponse()));
}
private void givenFailureApiResponse() throws Exception {
givenApiResponse(HttpStatus.OK, asJson(mockFailureResponse()));
}
private void givenErrorApiResponse() throws Exception {
givenApiResponse(HttpStatus.INTERNAL_SERVER_ERROR, Strings.EMPTY);
}
private void givenApiResponse(HttpStatus httpStatus, String responseBody) throws Exception {
server.expect(requestTo(API_URL))
.andExpect(method(HttpMethod.POST))
.andExpect(content().json(asJson(mockFooRequest())))
.andRespond(withStatus(httpStatus).contentType(MediaType.APPLICATION_JSON).body(responseBody));
}
private FooRequest mockFooRequest() {
return FooRequest.newInstance(ID);
}
private FooResponse mockSuccessResponse() {
return mockFooResponse("SUCCESS");
}
private FooResponse mockFailureResponse() {
return mockFooResponse("ERROR");
}
private FooResponse mockFooResponse(String status) {
FooResponse response = new FooResponse();
response.setStatus(status);
response.setId(ID);
return response;
}
private String asJson(Object obj) throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(obj);
}
}