Course contentsShow
← C#
Lesson 1663 of 1,90815. Software Quality and TestingFree lesson

Testing Third-Party API Integrations

Use proxy tools or record-replay tools to simulate unreliable external services.

In this lesson, you will learn how to stabilize your integration tests by using proxy and record-replay tools to simulate the erratic behavior of external dependencies.

The Challenge of External APIs

When testing integrations, relying on a live third-party API is a recipe for brittle tests. Network latency, rate limiting, and unexpected downtime often cause "flaky tests" that fail for reasons outside your codebase. While HttpMessageHandler mocking is great for unit tests, integration tests often require a more realistic environment where the network stack is actually exercised.

Simulating Reliability with Proxies

Instead of mocking the client inside your code, you can use a Proxy Tool (like WireMock.Net or MockServer). These tools sit between your application and the external API. During development, you can point your application settings to the proxy's URL instead of the real API.

The Record-Replay pattern is particularly powerful here:

  1. Record: You configure the proxy to forward requests to the actual third-party service and save the responses.
  2. Replay: Once you have a set of "golden" responses, you disconnect from the real API. The proxy serves the recorded responses instantly, ensuring your tests are deterministic and offline-capable.

Example: WireMock.Net

You can set up a proxy stub within your WebApplicationFactory to force a timeout or return a specific error code to verify your app’s resilience:

var server = WireMockServer.Start();

// Configure the proxy to simulate a 500 error
server
  .Given(Request.Create().WithPath("/api/data").UsingGet())
  .RespondWith(Response.Create().WithStatusCode(500));

// Now your application tests how it handles the failure
var client = factory.CreateClient();
var response = await client.GetAsync("/MyService/GetData");

Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);

By using a proxy, you decouple your test suite from the stability of external vendors while maintaining the "black-box" feel of a true integration test. This allows you to simulate edge cases—like massive payloads or slow timeouts—that are nearly impossible to trigger against a live production API.

Key Takeaway: Use proxy-based record-replay tools to turn non-deterministic external API dependencies into stable, repeatable, and local-only integration test assets.