Contract Testing Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Contract Testing runs in O(n) time and O(n) space, in Swift as in every other language.
- ✓Foundation offers nothing for this. PactSwift (SwiftPM package github.com/surpher/PactSwift) is the consumer-side standard and wraps the same Rust core through PactSwiftMockServer.
- ✓Everything happens inside mockService.run { baseURL, done in ... }, and done() must be called on every path including error branches; reviewers check that before anything else.
- ✓The Swift trap: Codable is stricter than the contract. A non-optional stored property means a missing key throws DecodingError.keyNotFound, so a provider that legitimately omits a nullable field breaks the consumer even though the pact verified, because the mock returned your example and your example always had the key.
- ✓PactSwift talks to a Rust mock server over loopback, so the Swift-side cost is JSONDecoder plus ARC traffic, never matching.
What Contract Testing actually is
Contract Testing in Swift: what you actually reach for
Swift implementation
import XCTest
import PactSwift
final class OrderClientPactTests: XCTestCase {
var mockService: MockService!
override func setUp() {
super.setUp()
mockService = MockService(consumer: "ios", provider: "orders")
}
func testFetchesAnOrder() {
mockService
.uponReceiving("a request for order 42")
.given("order 42 exists")
.withRequest(method: .GET, path: "/orders/42")
.willRespondWith(
status: 200,
body: [
"id": Matcher.SomethingLike(42),
"lines": Matcher.EachLike(["sku": Matcher.SomethingLike("ABC")])
]
)
mockService.run(timeout: 5) { baseURL, done in
// Order.discount must be Optional if the provider may omit it:
// a non-optional property throws DecodingError.keyNotFound.
OrderClient(baseURL: baseURL).fetch(42) { result in
defer { done() } // every path, or this just times out
guard case .success(let order) = result else {
return XCTFail("decode failed: \(result)")
}
XCTAssertEqual(order.id, 42)
}
}
}
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Contract Testing?
Foundation offers nothing for this. PactSwift (SwiftPM package github.com/surpher/PactSwift) is the consumer-side standard and wraps the same Rust core through PactSwiftMockServer. import PactSwift, then MockService(consumer: "ios", provider: "orders") with .uponReceiving(...).given(...).withRequest(method: .GET, path: ...).willRespondWith(status: 200, body: [...]). Matchers are Matcher.SomethingLike, Matcher.EachLike and Matcher.RegexLike, with ExampleGenerator values for things like random UUIDs. Provider verification for a Swift backend is not done from XCTest: run the Rust pact_verifier_cli against the running service.
What is the most common Swift mistake when implementing Contract Testing?
Codable is stricter than the contract. A non-optional stored property means a missing key throws DecodingError.keyNotFound, so a provider that legitimately omits a nullable field breaks the consumer even though the pact verified, because the mock returned your example and your example always had the key. Declare anything not required as Optional. Equally, JSONDecoder's keyDecodingStrategy must be identical in the test and in the shipped client, or .convertFromSnakeCase rewrites user_id to userId in exactly one of the two places. And a missing done() does not fail the test, it hangs until the XCTest timeout, which in CI reads as a flaky machine rather than a contract defect.
How does Contract Testing actually perform in Swift?
PactSwift talks to a Rust mock server over loopback, so the Swift-side cost is JSONDecoder plus ARC traffic, never matching. Codable conformance is synthesised at compile time so decoding is not reflective, but every String and Array in the decoded value is a heap allocation with retain and release pairs; a large EachLike fixture shows up as ARC churn in Instruments long before it shows as CPU. Passing the decoded struct around copies it field by field rather than retaining the struct itself; that copy stays cheap only because its String and Array fields are references to reference-counted buffers, which are duplicated only when something mutates them. Simulator and test-bundle launch dominate wall time anyway. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.