0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · Lección

Pruebas de API externas con WireMock

Pruebe mediante integración el código que llama a servicios HTTP externos simulando esos servicios con WireMock en lugar de acceder a la red.

Pruebas de API externas con WireMock es una lección gratuita de Testing Mastery: JUnit, Mockito & Integration Tests en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Testing Mastery: JUnit, Mockito & Integration Tests, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Testing Mastery: JUnit, Mockito & Integration Tests incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

The External Dependency Problem

Integration tests often touch real collaborators, but calling a live third-party API is slow, flaky, and may cost money. WireMock runs a local HTTP server you can program to mimic that API.

What WireMock Provides

WireMock lets you:

  • Stub HTTP responses for specific requests
  • Simulate delays, errors, and edge cases
  • Verify that your code made the expected calls

Starting a WireMock Server

In JUnit you start WireMock on a port (or a random one) before tests run.

WireMockServer server =
    new WireMockServer(options().dynamicPort());
server.start();

Stubbing a Response

Tell WireMock how to respond to a request using its fluent builder.

server.stubFor(get(urlEqualTo("/users/1"))
    .willReturn(aResponse()
        .withStatus(200)
        .withBody("{\"id\":1}")));

Pointing Your Client at WireMock

Configure the code under test to use WireMock's base URL. Using the dynamic port keeps tests isolated.

String baseUrl =
    "http://localhost:" + server.port();
UserClient client = new UserClient(baseUrl);

Exercising the Code

Now call your client. It hits WireMock, which returns the stubbed payload, and your assertions check the parsed result.

User u = client.fetch(1);
assertEquals(1, u.getId());

Simulating Failures

Return a 500 or a malformed body to test your error handling and retries.

server.stubFor(get(urlEqualTo("/users/2"))
    .willReturn(aResponse().withStatus(500)));

Simulating Latency

Add a fixed delay to verify timeout handling.

server.stubFor(get(anyUrl())
    .willReturn(aResponse()
        .withFixedDelay(3000)));

Verifying Requests

WireMock can assert that your code actually made a call with the right method, path, and headers.

server.verify(getRequestedFor(
    urlEqualTo("/users/1")));

Cleaning Up

Stop the server after tests, and reset stubs between tests so they stay independent.

server.resetAll();
server.stop();

Where It Fits

WireMock sits between unit tests (which mock objects) and full E2E tests (which use real services). It gives realistic HTTP behavior without external dependencies.

Quick Check

What is the main reason to use WireMock in integration tests?

Recap

You learned to test external API calls:

  • WireMock runs a local programmable HTTP server
  • Stub responses, errors, and delays with its builder
  • Point your client at the dynamic port
  • Verify requests and reset between tests

Preguntas frecuentes

¿La lección «Pruebas de API externas con WireMock» es gratis?

Sí — el texto completo de «Pruebas de API externas con WireMock» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Testing Mastery: JUnit, Mockito & Integration Tests, actualiza a CoddyKit PRO. El curso de Testing Mastery: JUnit, Mockito & Integration Tests incluye 4 lecciones en total.

¿Qué aprenderé en «Pruebas de API externas con WireMock»?

Pruebe mediante integración el código que llama a servicios HTTP externos simulando esos servicios con WireMock en lugar de acceder a la red. Practicas Testing Mastery: JUnit, Mockito & Integration Tests con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Testing Mastery: JUnit, Mockito & Integration Tests?

No se requiere experiencia previa. Testing Mastery: JUnit, Mockito & Integration Tests en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Pruebas de API externas con WireMock»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Testing Mastery: JUnit, Mockito & Integration Tests?

Sí. Cada lección de Testing Mastery: JUnit, Mockito & Integration Tests incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Pruebas unitarias frente a pruebas de integración
  2. Configuración de pruebas de integración
  3. Pruebas de interacciones con bases de datos
  4. Pruebas de API externas con WireMock
← Volver a Testing Mastery: JUnit, Mockito & Integration Tests