WireMock Integration Testing with Spring Boot

In modern applications, your services often communicate with external APIs — payment gateways, third-party authentication, messaging platforms, etc. During integration testing, relying on these actual external systems can make your tests:

  • Slow
  • Flaky
  • Dependent on internet access

Enter WireMock, a powerful HTTP mocking tool that lets you stub external API behavior in your integration tests. In this post, you’ll learn how to implement WireMock Integration Testing with Spring Boot and gain full control over external service responses.

WireMock Integration Testing with Spring Boot

⚙️ Project Setup

Let’s assume we’re building a CustomerService that calls an external “CRM API” to fetch user data. We’ll mock this external API using WireMock.

🧾 Maven Dependencies

Add these to your pom.xml:

📁 Package: com.kscodes.springboot

Let’s set up our project.

Customer.java

CustomerService.java

RestTemplateConfig.java

🧪 Writing the WireMock Integration Test

Here’s how to write a test using WireMock Integration Testing with Spring Boot:

💡 How It Works

  • @WireMockTest(httpPort = 8081) starts an embedded WireMock server
  • We override the crm.api.url to hit WireMock, not the real CRM
  • stubFor(...) defines the behavior of the mock endpoint
  • We validate that CustomerService correctly handles the mock response

📚 Advantages of WireMock Integration Testing with Spring Boot

FeatureBenefit
🧪 Fully isolatedNo dependency on real APIs
⚡ Fast and repeatableMocking gives full control
🧩 Easy to customizeSimulate 200, 404, 500 responses
🔄 Test edge casesSimulate timeouts and delays

⚠️ Bonus: Testing Error Scenarios

You can easily test how your service reacts to a 404 Not Found:

Test logic would assert that an exception or null is handled gracefully.

✅ Best Practices

  • Use @WireMockTest over manual server spin-up for simplicity
  • Externalize API URLs using @Value and profiles
  • Add delay simulation: .withFixedDelay(2000)
  • Store stubs in files for reuse with WireMockServer.loadMappingsFrom(...)

📚 Summary

In this post, you learned how to use WireMock Integration Testing with Spring Boot to isolate and simulate external APIs during testing. You now know how to:

  • Configure WireMock in tests
  • Stub custom HTTP responses
  • Inject mock endpoints using dynamic properties
  • Handle API failures and edge cases

WireMock gives you confidence that your service will behave correctly even when APIs are slow, fail, or respond unexpectedly.