In the last few years, we improved our test coverage a lot at the lower levels, but our end-to-end (E2E) tests were not that great. Because of that, after one client incident, we started to rethink how to do E2E testing.

Our main challenge was that we integrate with banks, and most banks don’t have a sandbox. Even when they do, the sandbox is often too limited to test behaviors outside of our control. Believe it or not, sometimes their sandbox doesn’t work the way it is supposed to, so we are not sure if the problem is in our code or in the bank’s sandbox. And when the sandbox works, it is often slow and unreliable, so we cannot run our E2E tests against it in CI before each daily deployment.

After a lot of thought and exploration, our solution was to build mocks that imitate what the banks do. We brought the banks in-house, under our control, so we could simulate some scenarios and make sure that our services were working.

Before getting into how we did it, let’s look at where E2E tests fit in the testing picture. On top of the famous testing pyramid, we have the end-to-end tests, which guarantee that all the services involved are correctly connected and everything is working as expected at the highest level.

Testing pyramid with unit tests at the base, service and consumer driven tests, and end to end tests on top

Sam Newman in Building Microservices - Testing Pyramid

We all know that most things should be tested at the unit and integration levels. For E2E, I like to have just a few happy path scenarios that test the integration between the services. Not all the scenarios. End-to-end tests take longer and are flakier than the other tests, so we need fewer of them, testing only what we cannot assert at the lower levels. We should make sure that we catch most of the problems on the lower layers so the last one is just a broader integration test with all the parts.

Still, they are worth the effort:

  • Scaling for growth: as we add more features, manual testing becomes impossible, and automated tests catch the issues.
  • Faster iteration: good regression coverage lets us move faster without sacrificing quality.
  • Cost efficiency: catching bugs early in development is exponentially cheaper than fixing production incidents.
  • Incident reduction: bugs are caught before the deployment, not by our customers.
  • Documentation: E2E tests are living documentation of the expected system behavior.
  • Developer experience: reliable tests catch mistakes, so developers can change things without fear of breaking them.

What is an end-to-end test?

The best definition I know comes from the book Unit Testing: Principles, Practices, and Patterns:

The line between end-to-end testing and integration testing is blurred at times, but in general, an integration test works with only one or two out-of-process dependencies. On the other hand, an end-to-end test works with all out-of-process dependencies, or with the vast majority of them. Hence the name end-to-end, which means the test verifies the system from the end user’s point of view, including all the external applications this system integrates with.

E2E tests are black box: they run from outside the code and use only the public APIs, as a real client would. Unlike integration tests, which can be written in the same code repository as the services and run the application directly in the tests, E2E tests live in a different repository and run against the container images deployed in the Kubernetes cluster. An integration test can check the database to assert a result, while an E2E test can only check what the public APIs return.

What should an E2E test test?

If our features are already covered by unit tests, and the main flows are covered by integration tests, what more do we need to test?

E2E tests verify the system from the end user’s point of view, so they test the functional behavior. Also, any scenario that was not possible to cover with unit or integration tests needs to be covered with E2E tests.

Choosing a mock server

To bring the banks in-house, we needed something to play their role: either a container or pod running alongside our services, or an external service we call over HTTPS.

We already used MockServer in some E2E tests, but the way we used it fell short:

  • No stateful sequences: we couldn’t simulate a payment moving from sent to processing to settled.
  • Hardcoded routing: each expectation was a fixed request and response, with little dynamic behavior.
  • Test pollution: every setup needed a manual clear(), which was easy to forget.
  • Limited request validation: it didn’t check the body structure, headers or authentication the way a bank would.
  • No configuration as code: the mock definitions couldn’t be versioned separately from the tests.
  • No standard: different tests used different mock servers.

After evaluating WireMock, Hoverfly, Prism (from Stoplight) and Testcontainers, we chose Mountebank because it was the only one where the state is fully programmable, through its inject functions. WireMock and Hoverfly only offer simple state machines, and the others needed an external state store or didn’t support state at all.

Mocking the banks with Mountebank

Mountebank runs as a separate pod in our Kubernetes cluster, so our services talk to it over the network, exactly as they talk to a real bank. Each bank is an “imposter” listening on its own port, with its own protocol and certificates, so a single Mountebank instance can simulate many banks at the same time. The first bank mock was working in less than a week, and in a few months we had many banks, all in one repository. The teams that work on each bank write its mock.

Technically, we could also use it to mock our own services in integration tests, but as the name says, it has to be a “bank”: Mountebank 😅

Diagram: the E2E tests call the public APIs of our services in the CI environment, which call Mountebank bank imposters in the same cluster over HTTPS, and a separate bank sandbox suite calls the real bank sandbox

The E2E tests only talk to our public APIs, and our services talk to Mountebank instead of the banks

Each bank mock follows the bank’s API specs: the OpenAPI spec when the bank publishes one, or the specs the bank gives us when we sign the contract. Specs can be wrong or out of date, so for the banks that have a sandbox, a separate suite runs against it and catches the gaps between the mock and the real bank.

What made us choose Mountebank:

  • Dynamic responses: each endpoint can run a JavaScript function that validates the request and builds the response, so the mock can reject a bad header or body the same way the bank would.
  • State: each imposter has an in-memory store, so a payment submitted in one call can be queried and reconciled in the next calls.
  • Configuration as code: the mock definitions are versioned and evolve with the bank specs.
  • Introspection: we can query every request an imposter received, during or after a test.

It has its limitations too:

  • No timers: it can’t run code on a schedule, so a bank that pushes a callback later needs a workaround, such as a cron job calling Mountebank’s admin API.
  • Isolated imposters: each imposter has its own state, so two banks can’t share data, and an HTTP imposter can’t coordinate with a TCP one or trigger a file.
  • State lives in memory: restarting Mountebank wipes it.
  • Slow functions block: a long-running inject function delays the response.
  • Minimal UI: its web pages only list the imposters and logs; everything else goes through its APIs.

An imposter routes each request to a function:

{
  "port": 4545,
  "protocol": "https",
  "name": "Bank Mock",
  "recordRequests": true,
  "stubs": [
    {
      "predicates": [{ "equals": { "method": "POST", "path": "/payments" } }],
      "responses": [{ "inject": "<%- inject('bank/imposter/functions/create-payment.js') %>" }]
    },
    {
      "predicates": [{ "equals": { "method": "GET" } }, { "matches": { "path": "^/payments/[^/]+$" } }],
      "responses": [{ "inject": "<%- inject('bank/imposter/functions/get-payment.js') %>" }]
    }
  ]
}

And the function validates the request and keeps the payment in the imposter’s state:

function (request, state, logger) {
    const payment = JSON.parse(request.body);
    if (!payment.amount) {
        return { statusCode: 400, body: JSON.stringify({ error: 'amount is required' }) };
    }
    state.payments = state.payments || {};
    const id = 'PMT-' + (Object.keys(state.payments).length + 1);
    state.payments[id] = { ...payment, id, status: 'ACCEPTED' };
    return {
        statusCode: 201,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(state.payments[id])
    };
}

When our services later call the bank to reconcile, another function reads the same payment back from the state:

function (request, state, logger) {
    const id = request.path.split('/')[2];
    const payment = (state.payments || {})[id];
    if (!payment) {
        return { statusCode: 404, body: JSON.stringify({ error: 'payment not found' }) };
    }
    return {
        statusCode: 200,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payment)
    };
}

The mock decides what the bank answers, including the errors and edge cases a real sandbox doesn’t let us trigger. The mock also continues the caller’s trace, so its requests show up in our tracing tool next to the services that called it.

Testing specific scenarios

We pass an account number, and that triggers the specific behavior we want to test. For example, one test account returns only current-day transactions, another only prior-day ones, and another both.

These behaviors are fixed on purpose. The same account always gets the same answer, so the tests are reproducible: when one fails, something changed in our services, not in the mock.

The same works for errors. These account numbers make the mock fail the way a bank can, so we can test how our services handle it:

const scenarios = {
    '100000500': { statusCode: 500 },  // bank is down
    '100000504': { statusCode: 504 },  // bank times out
    '100000429': { statusCode: 429 },  // rate limited
    '100000403': { statusCode: 403 }   // account not entitled
};

function (request, state, logger) {
    const accountId = request.path.split('/')[3];
    if (scenarios[accountId]) {
        return scenarios[accountId];
    }
    // ...normal response
}

I know these account numbers are not easy to maintain, but it is the best trade-off.

The test framework

Our E2E tests were spread across different places, written by different teams. The goal was to consolidate them into a single framework that serves all teams, with one common way of writing E2E tests.

The requirements were:

  • CI/CD integration: tests run automatically in the pipelines, and a failed test blocks the deployment.
  • Local execution: developers must be able to run the tests easily on their machines.
  • Environment flexibility: the same tests can point to a local environment or to a deployed CI environment.
  • Isolation: the tests live in a new, separate repository, with no dependencies on our internal libraries.

The stack is:

  • Test runner: TestNG
  • API calls: REST Assured
  • Assertions: AssertJ
  • Reporting: Allure, which keeps the test history across runs
  • Language: Java
  • Mocking external services: Mountebank
  • Test data: YAML files plus API calls

The tests are organized into Gradle modules, one per bank and one per product. Most tests are grouped by product, not by service, because each test follows a flow from the user’s perspective, which usually crosses several services. The bank modules cover what is specific to each bank, as banks offer different products and behave differently. The request and response POJOs are copied into the test repository instead of imported, to keep it isolated and to tailor them for testing.

A test looks like this. It creates a payment from the account that makes the mock time out, then polls the public API until the payment fails. The await(), from Awaitility, is there because the payment goes through several services asynchronously:

@Test
@Description("A payment fails when the bank times out")
public void paymentFailsWhenBankTimesOut() {
    String paymentId = given()
            .auth().oauth2(clientToken)
            .contentType(ContentType.JSON)
            .body(payment().fromAccount("100000504").amount("150.00").build())
            .post("/payments")
            .then().statusCode(201)
            .extract().path("id");

    await().atMost(Duration.ofMinutes(2)).untilAsserted(() ->
            assertThat(getPayment(paymentId).status()).isEqualTo("FAILED"));
}

Locally, Mountebank runs in Docker next to the rest of our services, just like in CI it runs next to them in Kubernetes. A developer can run one module with ./gradlew :products:payments:test, or a single test from the IDE.

Test data

We use a hybrid approach to create the test data:

  • YAML for the base entities: foundational entities such as service providers, users, integrations, products and dynamic configurations are loaded from YAML files before the tests run. Creating them through the APIs made the earlier test runs flaky, and the YAML setup proved much more reliable in CI. The loader upserts the data, and placeholders are resolved per environment.
  • API calls for everything else: entities that change per test, such as clients, payments and extra bank accounts, are created directly with REST Assured, which keeps the tests isolated and able to run in parallel.

Each module has its own users and service providers, so the tests don’t collide with each other.

The YAML is also where a bank integration is pointed at the mock instead of the real bank:

service-providers:
  Bank_SP:
    integrations:
      "Bank API":
        configs:
          apiBaseUrl: "{{ http_bank_mock_server_url }}/payments/v1"
          authTokenApiUrl: "{{ http_bank_mock_server_url }}/oauth2/token"

Running in CI

Every day, our deployment pipeline deploys the latest version of the services to a CI environment and runs the whole E2E API suite against it, with a matrix strategy that runs each module as a separate job in parallel. The deployment only moves on if it passes. The whole suite takes less than an hour, and it rarely fails. Where a bank does have a sandbox, a separate suite runs against it too. On pull requests to the test repository, only the changed modules run.

Every run fetches the latest version of the test repository, and Allure publishes a report with the history of the runs, the expected and actual results of each failure, and the line in the code where it failed.

Allure report chart showing the passed, failed and skipped tests in each of the last ten runs

Allure report with the history of the last runs

Lessons learned

  • Investigate flaky tests. A flaky E2E test might be pointing to a real issue in the application, such as a slow API, and not just a bad test.
  • Retry failed tests. They absorb intermittent network glitches or brief unavailability of a service.
  • No shared state between tests. Reusing or changing objects across tests introduces flakiness and wrong results.
  • One test, many environments. The same test runs locally or in CI, against the mock or against a bank sandbox.
  • Black box as much as possible. E2E tests validate that the feature works from the end user’s perspective, not the inner workings of the services.
  • Never point the tests at production. They rely on users and data that only exist in the CI and local environments.

Was it worth it?

Yes. Since we rebuilt the E2E tests, we haven’t had another incident like the one that started all this, and the team is a lot more confident in each daily release.