TDD in Legacy Code - Maintainable Component Tests - Backend
Many Backend Teams write unmaintainable Backend Component Tests - coupled to the Backend API and ERP. I'll show you how to refactor these brittle tests.
📅 Join me: Clean Architecture for Backend Developers on Wed 26th Aug, 5:00 - 6:30 PM (CEST)
Backend Component Tests provide fast feedback
We’ve seen in the previous article Backend Component Tests in Legacy Code, that Component Tests can provide us with fast feedback. The Backend Team can test the Backend in isolation, by stubbing out External Systems (such as the ERP).
But they can be a maintenance nightmare!
In Backend Component Tests in Legacy Code, we illustrated the “simplest” Backend Component Test.
The simplest way to write a Backend Component Test is to stub the External System inline (with WireMock), call the Backend API directly (with WebTestClient), and read the response by digging into raw JSON paths.
@Test
void shouldCreateOrderWithTotalPrice() {
// Arrange
var productDto = new ProductDto(2.50);
var productDtoJson = objectMapper.writeValueAsString(productDto);
erpWireMockStub.stubFor(WireMock.get(“/products?sku=APPLE1001”)
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader(“Content-Type”, “application/json”)
.withBody(productDtoJson)));
var orderRequest = new OrderRequest(“APPLE1001”, 5);
// Act & Assert
webTestClient.post()
.uri(“/api/orders”)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(orderRequest)
.exchange()
.expectStatus().isCreated()
.expectBody()
.jsonPath(“$.totalPrice”).isEqualTo(12.5);
}The problem is that this test is coupled in three places at once: the ERP wire format (the WireMock stub), the Backend API endpoint (webTestClient.post().uri("/api/orders")), and the response (the raw $.totalPrice JSON path).
If the API endpoint changes, or the ERP’s wire format changes (a renamed field, a different status code), then many such tests may break, so we have to waste time fixing tests. The plumbing is also copy-pasted into every test.
How to write maintainable Backend Component Tests?
In this article, I’ll show you how to introduce layers of abstraction, i.e. Component Test Architecture, so that you spend much less time writing & maintaining these tests.
Here are the steps to introduce Maintainable Backend Component Tests in Legacy Code. You’ll get tasks to implement in your GitHub Sandbox Project. ⬇️⬇️⬇️


