Why Do APITests Fail?
• - Works locally but fails in CI/CD ❌
• - Mocks don't always behave like real APIs
• - Network issues and unreliable test environments
• - Shared test servers cause conflicts
3.
What is Testcontainers?
•- A library that provides lightweight, throwaway containers
for testing
• - Supports real dependencies like databases, message
brokers, and APIs
• - Works across Java, Python, Node.js, and .NET
4.
API Testing withTestcontainers
• - Spin up real API dependencies (e.g., WireMock, Postgres,
Kafka)
• - Ensure integration tests run in isolated environments
• - Make tests reliable, fast, and production-like
5.
Code Example –API Test
• ```java
• @Testcontainers
• public class MyApiTest {
• @Container
• static WireMockContainer wiremock = new WireMockContainer("wiremock/wiremock");
• @Test
• void shouldTestApi() {
• wiremock.stubFor(get(urlEqualTo("/test"))
• .willReturn(aResponse().withStatus(200).withBody("Hello")));
• Response response = given().get(wiremock.getBaseUrl() + "/test");
• assertEquals(200, response.getStatusCode());
• }
• }```
6.
Best Practices
• ✅Use lightweight images (Alpine-based)
• ✅ Clean up containers after tests
• ✅ Parallelize tests smartly to avoid slow execution
• ✅ Avoid shared test servers – make tests self-contained
7.
Key Takeaways
• ✅Testcontainers provides realistic, isolated, and reliable API
testing
• ✅ Works across different programming languages
• ✅ Helps eliminate flaky tests and CI/CD failures
• 🚀 Use real dependencies, not mocks, for better API tests!