Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What does 'do not mock types you do not own' mean, using a Spring RestClient or JDBC call as an example?

It means we should not mock third-party APIs such as Spring's RestClient or JDBC's Connection directly, because the mock encodes our assumptions about how they behave, and those assumptions can be wrong or can become wrong after an upgrade while the tests keep passing. Instead we wrap the third-party API in a small interface of our own, mock that interface in unit tests, and test the wrapper against the real thing with an integration test, for example with WireMock or Testcontainers.

Why this question is asked

This guideline comes from the authors of the book that popularised mock objects, and it is one of the most useful rules for keeping tests honest. Interviewers ask about it because the mistake it prevents is very common: tests that mock a fluent HTTP client or a JDBC chain, pass for years, and then miss a bug that any real call would have revealed. In this answer, we will see what a mocked RestClient test looks like and why it is fragile, understand the reasoning behind the rule, apply the wrapper pattern step by step, and test the wrapper against something real.

1A Quick Recap: What 'Types We Own' Means

A type we own is one whose code and behaviour our team controls: our services, our repositories, our interfaces. A type we do not own comes from somewhere else: Spring's RestClient, JDBC's Connection and ResultSet, an AWS SDK client, Jackson's ObjectMapper. We use them, but their behaviour is defined by someone else and changes when we upgrade.

When we mock a type, we write down how it behaves: 'when called like this, it returns that'. For our own types, we know the truth and can change both sides together. For a third-party type, the mock is our guess, and nothing checks that the guess matches reality.

2What a Mocked RestClient Test Looks Like

Suppose a service fetches an exchange rate over HTTP with Spring's RestClient, which has a fluent API: each call returns another object until we finally get the body. Mocking it directly means mocking the whole chain.

Java
// Production code
BigDecimal rate = restClient.get()
.uri("/rates/{from}/{to}", "EUR", "USD")
.retrieve()
.body(BigDecimal.class);
// Test that mocks the type we do not own
RestClient client = mock(RestClient.class, RETURNS_DEEP_STUBS);
when(client.get().uri("/rates/{from}/{to}", "EUR", "USD").retrieve().body(BigDecimal.class))
.thenReturn(new BigDecimal("1.08"));
assertEquals(new BigDecimal("1.08"), new RateService(client).rate("EUR", "USD")); // passes

Notice how much the test knows about RestClient: the exact order of calls, the uri() overload we used, and that body() returns the parsed value. Now think about what it does not know. What does retrieve() do when the server returns 404 or 503? It throws an exception (a subclass of RestClientResponseException, check your Spring version), but our mock never throws, so our error handling is untested. What if the JSON is an object like {"rate": 1.08} rather than a bare number? The real body() call fails to convert it; the mock returns 1.08 anyway.

3Why the Mock Lies After an Upgrade

The deeper problem is that the mock freezes our understanding at the moment we wrote it. When we upgrade Spring or the HTTP library, the real behaviour may change: a different exception type, different handling of empty bodies, a new default timeout. Our mocked tests keep passing, because they never talk to the real code. The tests are green, and they are green about a world that no longer exists.

The same applies to JDBC. Mocking Connection, PreparedStatement and ResultSet requires us to script every call, including next() returning true then false and getString("name") returning a value. The test will pass even if our SQL has a syntax error, uses a column that does not exist, or returns the rows in the wrong order. The database is exactly the part that would catch those bugs, and it is the part we replaced.

What a mocked third-party API cannot tell us
Real behaviourMocked RestClient or JDBC
HTTP 404 or 503 throws an exceptionnever throws unless we script it
JSON shape must match the target typereturns whatever value we stub
SQL syntax and column names are checkedany SQL string is accepted
Behaviour may change on upgradetests keep passing on old assumptions

4The Fix: Wrap It in Our Own Small Interface

Instead of letting RestClient spread through our services, we define an interface in our own language, describing what we need rather than how HTTP works. Then we write one class that implements it with RestClient. That class is called an adapter, because it adapts the third-party API to our interface.

Java
// The interface we own, in business terms
public interface ExchangeRates {
BigDecimal rate(String from, String to); // throws RateUnavailableException
}
// The adapter: the only class that knows about RestClient
class HttpExchangeRates implements ExchangeRates {
private final RestClient client;
HttpExchangeRates(RestClient client) { this.client = client; }
public BigDecimal rate(String from, String to) {
try {
return client.get().uri("/rates/{from}/{to}", from, to).retrieve().body(RateDto.class).rate();
} catch (RestClientException e) {
throw new RateUnavailableException(from, to, e);
}
}
}
// Unit test of the business logic: mocking our own type is safe
ExchangeRates rates = mock(ExchangeRates.class);
when(rates.rate("EUR", "USD")).thenThrow(new RateUnavailableException("EUR", "USD", null));
assertEquals(Price.unavailable(), new PricingService(rates).priceInUsd(item)); // passes

Notice what changed. The business test now mocks a one-method interface whose behaviour we define and document, including the exception it throws. It is easy to stub, and the stub cannot be wrong about a library, because no library is involved. All the knowledge about RestClient lives in one small class.

5Testing the Wrapper Against the Real Thing

The adapter still needs a test, and that test must use the real library against something that behaves like the real server. For HTTP, WireMock runs a small HTTP server inside the test that returns the responses we configure, so the real RestClient sends real requests, parses real JSON and throws real exceptions.

Java
@Test
void mapsServerErrorToRateUnavailable() {
wireMock.stubFor(get("/rates/EUR/USD").willReturn(aResponse().withStatus(503)));
var rates = new HttpExchangeRates(RestClient.create(wireMock.baseUrl()));
assertThrows(RateUnavailableException.class, () -> rates.rate("EUR", "USD")); // passes
}
@Test
void parsesTheRate() {
wireMock.stubFor(get("/rates/EUR/USD").willReturn(okJson("{\"rate\": 1.08}")));
assertEquals(new BigDecimal("1.08"), new HttpExchangeRates(RestClient.create(wireMock.baseUrl())).rate("EUR", "USD")); // passes
}
Step throughWhere each test talks to what
  1. Business logic testsmock ExchangeRates, the interface we own
  2. ExchangeRates interfaceour contract, in business terms
  3. HttpExchangeRates adapterthe only code that knows RestClient
  4. Adapter testsreal RestClient against WireMock or Testcontainers

4 layers, from the top down. Step through them one at a time.

For JDBC the equivalent is a repository class tested with Testcontainers against a real PostgreSQL. Now when we upgrade Spring or the driver, these few tests exercise the real library, and if its behaviour changed, they fail exactly where the change matters.

6Follow-up questions

Is it ever acceptable to mock a type we do not own?

Occasionally, for a trivial call where a wrapper would add nothing, or in legacy code as a temporary step. But for anything with real behaviour, such as HTTP, SQL or messaging, the wrapper and an integration test are worth it.

Is MockRestServiceServer a mock of a type we do not own?

It is Spring's own test support for RestTemplate and RestClient, so it is maintained alongside the client and exercises the real client code. It is a reasonable alternative to WireMock for adapter tests, while WireMock tests the real HTTP stack end to end.

Doesn't the wrapper add a layer of code?

Yes, one small class. In exchange, the rest of the code depends on a stable interface in business terms, the library can be upgraded or replaced in one place, and the tests are honest.

7Conclusion

In this answer, we saw that mocking a third-party type such as RestClient or a JDBC Connection writes our assumptions about it into the test, and those assumptions can be wrong from the start or become wrong after an upgrade while tests keep passing. The fix is to wrap the library in a small interface we own, mock that interface in business tests, and test the adapter against the real library with WireMock or Testcontainers.

What to say in the interviewAbout 70 seconds aloud

Open with

It means the mocks in my tests should describe types whose behaviour I control. If I mock Spring's RestClient chain or a JDBC Connection and ResultSet, the mock is my guess about how the library behaves.

Then, if they want more

My guess may be wrong from the start, for example the mock never throws on a 503 or accepts SQL with a wrong column name, and it can become wrong after an upgrade, while the tests stay green because they never touch the real library.

So instead I wrap the third-party API in a small interface of my own, like ExchangeRates with a rate method that throws a RateUnavailableException. One adapter class implements it with RestClient and translates its exceptions. Business tests mock ExchangeRates, which is safe because I define its contract.

And the adapter gets an integration test against something real: WireMock for HTTP, so the real client sends requests and parses JSON, or Testcontainers with a real PostgreSQL for JDBC code. That way upgrades are tested in one place, and the rest of the code depends on a stable interface.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What does 'do not mock types you do not own' mean, using a Spring RestClient or JDBC...": https://scrivio-interview-library.netlify.app/java/mocking/898ec6fe43/