DevPrep

All topics › Software testing

How to write mocks in Swift without frameworks: protocols, closures, spies?

Middle PRO

The gist

Swift has no runtime method swizzling for test doubles, so they are written by hand — and that is cheaper than it seems. Three techniques cover almost everything: a protocol + a double class that both records calls (spy) and returns a configurable answer (stub); a struct of closures, where each function of a dependency is replaced individually; and Result as the answer configuration, so one double checks both success and failure.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store