CodePark/ questions / Mocks, stubs, spies & fakes
START PRACTICINGPRACTICE
Backend question · Backend testing › Mocks, stubs, spies & fakes

What does "don't mock what you don't own" mean? How would you apply it to a service that uses the Stripe SDK?

It means: don't create test doubles of third-party APIs directly. For example, don't stub stripe.paymentIntents.create in every test.

Why? Your mock contains your guess about how the library behaves. If the guess is wrong, or the library changes, the tests stay green but production breaks. Also, large SDKs have many methods, so they are hard to fake.

Instead, wrap the library in an adapter that you own:

  • Define a PaymentGateway interface with charge(orderId, amount), which returns your own result type.
  • Implement it in a StripePaymentGateway class.
  • Business services depend on the interface, not on Stripe.
  • Their unit tests use a simple stub or fake of the interface.

Test the adapter itself with integration tests. Either run them against Stripe's test mode, or intercept the HTTP calls with nock or MSW. Use realistic responses, including errors and timeouts.

  • Mocking a third-party API puts your guesses about its behaviour into the tests.
  • Wrap the library in an adapter with an interface you own.
  • Mock or fake the adapter in business-logic tests.
  • Test the adapter with integration tests against a sandbox or intercepted HTTP.