</>

Technology

API Automation

Difficulty

Advanced

Interview Question

How do you mock failed API responses for testing error handling in your application?

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

ScenarioStatus CodePurpose
Server crash500Test graceful degradation
Resource missing404Test user-facing error message
Auth expired401Test auto-refresh or redirect
Rate limited429Test backoff/retry logic
Service unavailable503Test fallback mechanisms
Network timeoutN/ATest timeout handling

Follow AutomateQA

Related Topics