In my application, I have external third party API requests. I want to test my application with mocking this API requests.
My Service Class:
String API_URL = "https://external.com/v1/%s";
private CloseableHttpClient httpClient;
public Result executeRequest(String apiVersion, String subUrl, HttpMethod httpMethod)
{
try
{
HttpRequestBase httpRequest;
String url = String.format(API_URL, subUrl);
if (httpMethod.equals(HttpMethod.GET))
{
httpRequest = new HttpGet(url);
}
else if (httpMethod.equals(HttpMethod.POST))
{
httpRequest = new HttpPost(url);
((HttpPost) httpRequest).setEntity(new StringEntity(requestBody, "UTF-8"));
}
...
headers.forEach(httpRequest::setHeader);
HttpResponse response = httpClient.execute(httpRequest);
}
catch (IOException e)
{
logger.error("IO Error: {}", e.getMessage());
return handleExceptions(e);
}
}
To sum up for service class, requests can be get, post, delete, put. And this requests will be processed with headers or body parts. Then will be handled as http request.
My test class:
@SpringBootTest
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
public class ServiceTest
{
private static final String API_URL = "https://external.com/v1";
@Autowired
private Service service;
@Autowired
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
@Before
public void init()
{
mockServer = MockRestServiceServer.createServer(restTemplate);
}
@Test
public void getResult_successfully()
{
Result result = new Result();
mockServer.expect(ExpectedCount.once(),
requestTo("/subUrl"))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(gson.toJson(result))
);
Result returnResult = service.executeRequest("/subUrl", GET);
mockServer.verify();
assertThat(returnResult).isEqualTo(result);
}
}
When I implement it like above, mocking doesn't work. Any suggestion?
I know in here, MockRestServiceServer work only with restTemplate requests but I wonder there is a way to handle it with httpClient?
Note: I hope code snippets will be enough to understand the code in overall.