Тестирование внешних API с помощью WireMock
Проводите интеграционное тестирование кода, обращающегося к внешним HTTP-службам, подменяя эти службы с помощью WireMock вместо обращения к сети.
«Тестирование внешних API с помощью WireMock» — бесплатный урок Testing Mastery: JUnit, Mockito & Integration Tests на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Testing Mastery: JUnit, Mockito & Integration Tests, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Testing Mastery: JUnit, Mockito & Integration Tests содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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
Часто задаваемые вопросы
Урок «Тестирование внешних API с помощью WireMock» бесплатный?
Да — полный текст урока «Тестирование внешних API с помощью WireMock» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Testing Mastery: JUnit, Mockito & Integration Tests, подпишись на CoddyKit PRO. Курс Testing Mastery: JUnit, Mockito & Integration Tests содержит 4 уроков всего.
Чему я научусь в уроке «Тестирование внешних API с помощью WireMock»?
Проводите интеграционное тестирование кода, обращающегося к внешним HTTP-службам, подменяя эти службы с помощью WireMock вместо обращения к сети. Ты практикуешь Testing Mastery: JUnit, Mockito & Integration Tests с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Testing Mastery: JUnit, Mockito & Integration Tests?
Предыдущий опыт не требуется. Testing Mastery: JUnit, Mockito & Integration Tests на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Тестирование внешних API с помощью WireMock»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Testing Mastery: JUnit, Mockito & Integration Tests?
Да. Каждый урок Testing Mastery: JUnit, Mockito & Integration Tests включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Модульные и интеграционные тесты
- Настройка интеграционных тестов
- Тестирование взаимодействия с базами данных
- Тестирование внешних API с помощью WireMock