Answer
Scenario: Mocking Failed API Responses
To test how your application handles API failures, you need to simulate various error scenarios without actually breaking the real API.
Tools: WireMock (Java)
Add to pom.xml:
XML
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>2.35.0</version>
<scope>test</scope>
</dependency>
Setup WireMock Server
Java
public class MockApiTest {
@Rule
public WireMockRule wireMockRule = new WireMockRule(8089);
private String mockBaseUrl = "http://localhost:8089";
}
Mock 500 Internal Server Error
Java
@Test
public void testApplicationHandles500Error() {
// Setup stub
stubFor(get(urlEqualTo("/api/users"))
.willReturn(aResponse()
.withStatus(500)
.withHeader("Content-Type", "application/json")
.withBody("{ \"error\": \"Internal Server Error\" }")));
// Test your application''s behavior
Response response = given()
.when()
.get(mockBaseUrl + "/api/users");
assertEquals(response.getStatusCode(), 500);
assertEquals(response.jsonPath().getString("error"), "Internal Server Error");
// Verify your app shows a user-friendly error, not a crash
}
Mock 404 Not Found
Java
@Test
public void testApplicationHandles404() {
stubFor(get(urlPathMatching("/api/users/.*"))
.willReturn(aResponse()
.withStatus(404)
.withBody("{ \"message\": \"User not found\" }")));
Response response = given()
.when()
.get(mockBaseUrl + "/api/users/999");
assertEquals(response.getStatusCode(), 404);
}
Mock 401 Unauthorized
Java
@Test
public void testApplicationHandlesUnauthorized() {
stubFor(get(urlEqualTo("/api/profile"))
.willReturn(aResponse()
.withStatus(401)
.withBody("{ \"error\": \"Token expired\" }")));
// Verify app redirects to login
Response response = given().when().get(mockBaseUrl + "/api/profile");
assertEquals(response.getStatusCode(), 401);
}
Mock Network Failure / Slow Response
Java
@Test
public void testApplicationHandlesTimeout() {
stubFor(get(urlEqualTo("/api/users"))
.willReturn(aResponse()
.withStatus(200)
.withFixedDelay(10000) // 10 second delay
.withBody("{ \"data\": [] }")));
// Your app should timeout and show an appropriate message
given()
.config(RestAssured.config().httpClient(
HttpClientConfig.httpClientConfig()
.setParam(CoreConnectionPNames.SO_TIMEOUT, 5000))) // 5s timeout
.when()
.get(mockBaseUrl + "/api/users")
.then()
.time(lessThan(6000L)); // Verify timeout was triggered
}
Mock Flaky API (Intermittent Failures)
Java
@Test
public void testApplicationHandlesFlakyApi() {
// First call fails, second call succeeds
stubFor(get(urlEqualTo("/api/data"))
.inScenario("Flaky API")
.whenScenarioStateIs(Scenario.STARTED)
.willReturn(aResponse().withStatus(503))
.willSetStateTo("Second Call"));
stubFor(get(urlEqualTo("/api/data"))
.inScenario("Flaky API")
.whenScenarioStateIs("Second Call")
.willReturn(aResponse()
.withStatus(200)
.withBody("{ \"data\": \"success\" }")));
// First call
given().when().get(mockBaseUrl + "/api/data").then().statusCode(503);
// Second call (retry)
given().when().get(mockBaseUrl + "/api/data").then().statusCode(200);
}
Error Scenarios to Mock
| Scenario | Status Code | Purpose |
|---|---|---|
| Server crash | 500 | Test graceful degradation |
| Resource missing | 404 | Test user-facing error message |
| Auth expired | 401 | Test auto-refresh or redirect |
| Rate limited | 429 | Test backoff/retry logic |
| Service unavailable | 503 | Test fallback mechanisms |
| Network timeout | N/A | Test timeout handling |
