1 | initial version |
The method for creating unit tests for HttpServerErrorException and HttpClientErrorException depends on the programming language and testing framework being used. However, in general, the following steps can be followed:
For example, in Java using the Spring framework and JUnit, the following test case could be created:
@ExtendWith(MockitoExtension.class)
public class MyApiClientTest {
@Mock
private RestTemplate restTemplate;
@Test
public void testApiCallThrowsHttpServerErrorException() {
MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate);
server.expect(requestTo("/api/resource"))
.andRespond(withServerError());
MyApiClient client = new MyApiClient(restTemplate, "https://example.com");
HttpServerErrorException thrown = assertThrows(HttpServerErrorException.class, () -> {
client.getResource();
});
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, thrown.getStatusCode());
assertTrue(thrown.getMessage().contains("Server error"));
}
@Test
public void testApiCallThrowsHttpClientErrorException() {
MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate);
server.expect(requestTo("/api/resource"))
.andRespond(withStatus(HttpStatus.UNAUTHORIZED)
.body("Unauthorized"));
MyApiClient client = new MyApiClient(restTemplate, "https://example.com");
HttpClientErrorException thrown = assertThrows(HttpClientErrorException.class, () -> {
client.getResource();
});
assertEquals(HttpStatus.UNAUTHORIZED, thrown.getStatusCode());
assertTrue(thrown.getMessage().contains("Unauthorized"));
}
}