---
title: "iOS testing with Claude Code"
slug: ios-testing-with-claude-code
section: tech
date: 2026-10-21T07:58:00.000Z
canonical: https://roland.leth.ro/blog/tech/ios-testing-with-claude-code
description: "iOS testing with Claude Code: it writes tests fast, and left alone they confirm the code, bugs included. Where my tests come from, and how I check them."
---

Claude Code writes the code for my iOS apps, tests included, and it's really fast at the tests. Left alone, though, it writes them by reading the code it just wrote, so they check that the code does what it does. Bugs included.

Here’s what iOS testing with Claude Code looks like on [Digest][digest], the food journal I'm building: where the tests come from, how the code is split so a test can reach the logic, and a few tests that exist only because 2 files drifted apart.

(Running the tests, and what the simulator does to them, is in [the previous post][prev].)

## Circular tests

The easy way is usually to ask Claude Code for tests once a feature works. It reads the implementation and writes down what it sees: this input returns that, so the test expects that. If "that" is right, fine. If it's a bug, the test might expect the bug, and it'll actually defend it; the fix turns the test red, and a red test looks a lot like a regression.

That's circular testing. The test fails when the code _changes_, never when the code is wrong.

The good news about this is that it feels like Claude writes pretty good tests.

I don't remember an iOS case of this, to be honest, but I do have one at hand from this website, which is TypeScript. The shape doesn't really care about the language.

The site's admin checks the first bytes of every uploaded image to decide what format it actually is, instead of trusting the extension. AVIF and HEIC files both start with an `ftyp` box (the header of HEIF, the container format they share), which names a major brand and a list of compatible ones.

In May, the detector took `avif`, `avis` or `mif1` as the major brand of an AVIF, and a test fed it a `mif1` header and expected `image/avif`. But `mif1` is not AVIF only, it's the generic HEIF brand; some AVIF encoders also write it, and so do HEIC files. So a HEIC starting with it went through as an AVIF and got stored as an `.avif` no browser could render.

A code review flagged it at the end of September, and the finding contradicted a test, which is usually where you'd believe the test. 

But this time, the test was wrong. It had been written from the code, so it pinned `mif1` as valid and protected the bug since May.

So where does the expected value come from, for this example? Pretty much anywhere but the implementation: the spec, a decision I made, the platform's documentation or what an AVIF file actually is. A test written from the code can't know any of that, it just knows what the code _returns_.

My rules for Claude Code ([how they're set up][rules]) have 2 lines on this, in the tests section:

> Create tests based on logic, then check that implementation abides; don't write tests that simply follow existing code.
>
> Let tests drive the code's behavior, never its structure.

The rule alone isn't quite enough, though. Once tests are written, one that came from the code and one that came from the logic look _exactly_ the same, and a passing test is one more report to check rather than read (like the ones in [The model will tell you it worked when it didn’t][worked]).

The way to check is to break the code and watch the test fail (mutation testing, done by hand). Flip the guard, return the wrong value, delete a line, etc, then run the test, see it go red and put the code back.

One break at a time, though, since 2 breaks can hide each other. A fix on this site's admin replaced a text field's character limit with a count of its own, and checking it meant putting the old limit back _and_ breaking the new count. With both in, the old limit cut the pasted text short before the count ever saw it, and the test for the count passed anyway; broken one at a time, each went red.

## Logic a test can reach

A unit test can't call into a SwiftUI view's body, so whatever the view decides in there — an `if` over 2 `@State`s, a computed property picking a label — is only reachable through a render or a UI test. In Digest, every screen that decides something has a paired view model where decisions happen, and every view model a paired test file.

The threshold is in my Swift rules: a view gets a view model when it owns domain state, writes to the store, holds more than 3 properties _of its own_, or holds logic worth testing; any one is enough. A screen can hold nothing but presentation state and still decide something in a computed property, which should be moved to the view model, so it can be tested.

The same 2 shapes keep coming back. First, when an action starts a `Task`, I split it into a sync entry for the view and an awaited core, because a test can't really await a `Task` it never sees.

For example, Digest can show your weight from Apple Health, and a toggle in Settings asks for access when you turn it on:

```swift
func request( // ❶
   _ kind: HealthDataKind,
   from health: any HealthContextReading,
   revert: @escaping () -> Void
) {
   Task {
      await requestAccess(to: kind, from: health, revert: revert)
   }
}

/// The awaited body of `request(_:from:revert:)`.
func requestAccess( // ❷
   to kind: HealthDataKind,
   from health: any HealthContextReading,
   revert: () -> Void
) async {
   do {
      try await health.requestReadAccess(to: [kind])
      // [...]
   } catch {
      Log.health.error("Read authorization for \(String(describing: kind)) failed: \(error)")
      isRequestFailed = true
      revert()
   }
}
```

The toggle calls `request` (❶); the tests call `requestAccess` (❷) and await it.

Those tests are also a pretty good example of where the expected values come from. An app can't find out whether the user denied read access to Health (a denial looks just like a grant), so a denial has to leave the switch where the user put it, and only an actual error may bounce it:

```swift
@Test("A silent denial leaves the toggle where the user put it")
func silentDenialLeavesTheToggleOn() async {
   let viewModel = AppleHealthSettingsViewModel()
   var didRevert = false

   await viewModel.requestAccess(
      to: .weight,
      from: PreviewHealthContext(),
      revert: { didRevert = true }
   )

   #expect(!didRevert)
   #expect(!viewModel.isRequestFailed)
}
```

None of that is in `requestAccess`, it's in how `HealthKit` behaves. A test written by reading the implementation would most likely pin whatever the implementation happened to do.

Second, a boundary that can't run in a test host gets injected in `init`. For example, a `NotificationsSettingsViewModel` takes its `authorize` closure as a parameter to be mocked, and the real one prompts through `UNUserNotificationCenter`.

## Files that drift apart

A few of Digest's tests check no logic at all. They check that 2 things which have to agree still do; a single test written from only one of them can't prove anything.

For example, the `StoreKit` configuration file and the product identifiers in code are edited in different places. If I add a product to `Digest.storekit`, but forget the identifiers, nothing really breaks: the code still compiles, still runs, and quietly resolves no entitlement for it; in the sandbox, buying it unlocks nothing.

I had that happen a few months ago for [Digest][digest]: the lifetime product went into the config while `ProductID.all` still listed 2 identifiers, and nothing failed for 2 days.

So a suite now walks every `productID` in the config's JSON and checks both directions:

```swift
@Test("The config declares no product the code doesn't know about")
func configProductIDs_areAllKnownToTheCode() throws {
   let configured = try Self.configuredProductTypes()
   let unknown = Set(configured.keys).subtracting(EntitlementStore.ProductID.all)

   #expect(unknown.isEmpty, "\(unknown.sorted()) declared in Digest.storekit but unknown to ProductID.all")
}
```

The other direction starts with a line that's easy to skip:

```swift
// `#require` first: an empty set would let every containment check below pass silently,
// which is the one way this suite could go green while proving nothing.
try #require(configured.isEmpty == false)
```

If the file moves or the walk finds nothing, every "is it in there" check passes on an empty set. Same question as the broken guards above, from the other side: can this test pass while proving _nothing_?

## Traps in the test setup

The usual advice for `SwiftData` tests is an in-memory container, which is probably fine for an app without `CloudKit`. In Digest it wasn't enough: the test host is the app, entitlements and all, and `ModelConfiguration`'s `cloudKitDatabase` defaults to `.automatic`.

An in-memory store on `.automatic` (a debug sample journal in the app, not a test), running on my own device, mirrored _both ways_: it pulled my real journal into the sample one and pushed sample meals into my private iCloud database. Until the test helper said otherwise, every test container was CloudKit-backed too:

```swift
static func inMemory() throws -> ModelContainer {
   let configuration = ModelConfiguration(
      "test-\(UUID().uuidString)",
      isStoredInMemoryOnly: true,
      cloudKitDatabase: .none
   )

   return try ModelContainer(for: DigestSchema.schema, configurations: [configuration])
}
```

`.none` is what keeps `CloudKit` out; the in-memory flag doesn't. In hindsight, it makes sense, but initially I assumed in-memory is enough.

Comments can be a trap too. Digest had a timing test that checked a 10-year journal got analyzed within 2 seconds, and its comment said that budget was about 20× what the analysis takes. Then it failed during a busy full run, and I went looking: the 20× was the plan's target, under 100ms, which the engine never actually hit. Measured, the margin was about 4× when the budget was set, and about 2× later on. So a ratio in a comment now gets traced back to a dated measurement before anyone relies on it.

Everything above assumes I know what the right answer is. For the engine I built for Digest to find which food might be behind a symptom, I didn't know. I dropped the engine in the end, for unrelated reasons, but how I tested it is [the next post][next].

If you've got a better way to catch circular tests than breaking the code on purpose, I'd love to hear it ([@roland.leth.ro][] / [@rolandleth][])!

The other posts on Claude Code and iOS are listed in [Claude Code for iOS development][series].

[prev]: /blog/tech/claude-code-and-the-ios-simulator-what-breaks "Claude Code and the iOS Simulator: what breaks"
[next]: /blog/tech/testing-code-when-you-dont-know-the-right-answer "Testing code when you don’t know the right answer"
[series]: /blog/tech/claude-code-for-ios-development "Claude Code for iOS development"
[rules]: /blog/tech/claude-code-rules-hooks-and-skills-and-how-i-set-mine-up "Claude Code rules, hooks and skills, and how I set mine up"
[worked]: /blog/tech/the-model-will-tell-you-it-worked-when-it-didnt "The model will tell you it worked when it didn’t"
[digest]: /projects/digest "Digest"
[@roland.leth.ro]: https://bsky.app/profile/roland.leth.ro "@roland.leth.ro on Bluesky"
[@rolandleth]: https://x.com/rolandleth "@rolandleth on X"
