mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
831 lines
29 KiB
HTML
831 lines
29 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>ios-testing</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="alternate" type="text/markdown" href="/ios-testing.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/ios-testing">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/ios-testing.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>ios-testing</h1><p class="lede">Writing unit tests for iOS/macOS apps</p><h1>iOS Testing with Swift Testing Framework</h1>
|
|
<p><strong>Use this skill when:</strong></p>
|
|
<ul><li>Writing unit tests for iOS/macOS apps</li><li>Testing async/await code</li><li>Testing SwiftUI views and view models</li><li>Using Swift Testing framework (swift-testing)</li><li>Migrating from XCTest to Swift Testing</li></ul>
|
|
<h2>Swift Testing Basics</h2>
|
|
<h3>Writing Tests</h3>
|
|
<p>Use <code>@Test</code> attribute for test functions:</p>
|
|
<pre><code class="lang-swift">import Testing
|
|
|
|
@Test
|
|
func addition() {
|
|
let result = 2 + 2
|
|
#expect(result == 4)
|
|
}
|
|
|
|
@Test("Multiplication works correctly")
|
|
func multiplication() {
|
|
#expect(3 * 4 == 12)
|
|
}
|
|
|
|
// Test with custom display name
|
|
@Test("String concatenation", .tags(.stringTests))
|
|
func stringConcat() {
|
|
let result = "Hello" + " " + "World"
|
|
#expect(result == "Hello World")
|
|
}</code></pre>
|
|
<h3>Expectations</h3>
|
|
<p>Use <code>#expect</code> for assertions:</p>
|
|
<pre><code class="lang-swift">@Test
|
|
func expectations() {
|
|
// Boolean expectation
|
|
#expect(true)
|
|
#expect(!false)
|
|
|
|
// Equality
|
|
#expect(42 == 42)
|
|
#expect("hello" == "hello")
|
|
|
|
// Optional unwrapping
|
|
let value: Int? = 42
|
|
#expect(value != nil)
|
|
|
|
// Throwing expectation
|
|
#expect(throws: DivisionError.self) {
|
|
try divide(10, by: 0)
|
|
}
|
|
|
|
// Non-throwing expectation
|
|
#expect {
|
|
try parseJSON(validData)
|
|
} throws: { error in
|
|
false // Expect no error
|
|
}
|
|
}</code></pre>
|
|
<h3>Parameterized Tests</h3>
|
|
<p>Test with multiple inputs:</p>
|
|
<pre><code class="lang-swift">@Test(arguments: [1, 2, 3, 4, 5])
|
|
func testSquare(number: Int) {
|
|
let result = number * number
|
|
#expect(result == number * number)
|
|
}
|
|
|
|
@Test(arguments: [
|
|
("hello", "HELLO"),
|
|
("world", "WORLD"),
|
|
("Swift", "SWIFT")
|
|
])
|
|
func testUppercase(input: String, expected: String) {
|
|
#expect(input.uppercased() == expected)
|
|
}
|
|
|
|
// Multiple parameter sets
|
|
@Test(arguments: [1, 2, 3], [10, 20, 30])
|
|
func testAddition(a: Int, b: Int) {
|
|
let result = a + b
|
|
#expect(result == a + b)
|
|
}</code></pre>
|
|
<h2>Testing Async Code</h2>
|
|
<h3>Basic Async Tests</h3>
|
|
<p>Test async functions:</p>
|
|
<pre><code class="lang-swift">@Test
|
|
func testAsyncFetch() async throws {
|
|
let service = UserService()
|
|
let user = try await service.fetchUser(id: testUserId)
|
|
|
|
#expect(user.name == "Test User")
|
|
#expect(user.email.contains("@"))
|
|
}
|
|
|
|
@Test
|
|
func testParallelFetch() async throws {
|
|
let service = UserService()
|
|
|
|
async let user1 = service.fetchUser(id: id1)
|
|
async let user2 = service.fetchUser(id: id2)
|
|
|
|
let users = try await [user1, user2]
|
|
|
|
#expect(users.count == 2)
|
|
#expect(users[0].id != users[1].id)
|
|
}</code></pre>
|
|
<h3>Testing Actors</h3>
|
|
<p>Test actor state and isolation:</p>
|
|
<pre><code class="lang-swift">@Test
|
|
func testActorState() async {
|
|
let cache = UserCache()
|
|
|
|
await cache.setUser(testUser)
|
|
let retrieved = await cache.getUser(id: testUser.id)
|
|
|
|
#expect(retrieved?.id == testUser.id)
|
|
#expect(retrieved?.name == testUser.name)
|
|
|
|
await cache.clear()
|
|
let afterClear = await cache.getUser(id: testUser.id)
|
|
#expect(afterClear == nil)
|
|
}
|
|
|
|
@Test
|
|
func testConcurrentAccess() async {
|
|
let counter = Counter()
|
|
|
|
await withTaskGroup(of: Void.self) { group in
|
|
for _ in 0..<100 {
|
|
group.addTask {
|
|
await counter.increment()
|
|
}
|
|
}
|
|
}
|
|
|
|
let final = await counter.value
|
|
#expect(final == 100)
|
|
}</code></pre>
|
|
<h3>Testing with Timeouts</h3>
|
|
<p>Test time-sensitive code:</p>
|
|
<pre><code class="lang-swift">@Test(.timeLimit(.seconds(5)))
|
|
func testWithTimeout() async throws {
|
|
let result = try await longRunningOperation()
|
|
#expect(result != nil)
|
|
}
|
|
|
|
@Test
|
|
func testOperationCompletes() async throws {
|
|
let start = Date()
|
|
|
|
try await Task.sleep(for: .milliseconds(100))
|
|
|
|
let elapsed = Date().timeIntervalSince(start)
|
|
#expect(elapsed >= 0.1)
|
|
#expect(elapsed < 0.2)
|
|
}</code></pre>
|
|
<h2>Testing View Models</h2>
|
|
<h3>Observable View Models</h3>
|
|
<p>Test SwiftUI view models:</p>
|
|
<pre><code class="lang-swift">@Test
|
|
func testViewModelLoading() async {
|
|
let mockService = MockUserService()
|
|
mockService.userToReturn = User(id: UUID(), name: "Test")
|
|
|
|
let viewModel = UserViewModel(service: mockService)
|
|
|
|
#expect(viewModel.user == nil)
|
|
#expect(viewModel.isLoading == false)
|
|
|
|
await viewModel.loadUser()
|
|
|
|
#expect(viewModel.user != nil)
|
|
#expect(viewModel.user?.name == "Test")
|
|
#expect(viewModel.isLoading == false)
|
|
}
|
|
|
|
@Test
|
|
func testViewModelError() async {
|
|
let mockService = MockUserService()
|
|
mockService.shouldThrowError = true
|
|
|
|
let viewModel = UserViewModel(service: mockService)
|
|
|
|
await viewModel.loadUser()
|
|
|
|
#expect(viewModel.user == nil)
|
|
#expect(viewModel.errorMessage != nil)
|
|
}</code></pre>
|
|
<h3>Testing State Changes</h3>
|
|
<p>Verify state transitions:</p>
|
|
<pre><code class="lang-swift">@Observable
|
|
final class TaskViewModel {
|
|
enum State {
|
|
case idle
|
|
case loading
|
|
case loaded([Task])
|
|
case error(Error)
|
|
}
|
|
|
|
var state: State = .idle
|
|
|
|
func load() async {
|
|
state = .loading
|
|
|
|
do {
|
|
let tasks = try await fetchTasks()
|
|
state = .loaded(tasks)
|
|
} catch {
|
|
state = .error(error)
|
|
}
|
|
}
|
|
}
|
|
|
|
@Test
|
|
func testStateTransitions() async {
|
|
let viewModel = TaskViewModel()
|
|
|
|
// Initial state
|
|
if case .idle = viewModel.state {
|
|
// Pass
|
|
} else {
|
|
Issue.record("Expected idle state")
|
|
}
|
|
|
|
// Start loading
|
|
Task {
|
|
await viewModel.load()
|
|
}
|
|
|
|
// Eventually reaches loaded state
|
|
try await Task.sleep(for: .milliseconds(100))
|
|
|
|
if case .loaded(let tasks) = viewModel.state {
|
|
#expect(!tasks.isEmpty)
|
|
} else {
|
|
Issue.record("Expected loaded state")
|
|
}
|
|
}</code></pre>
|
|
<h2>Testing SwiftUI Views</h2>
|
|
<h3>Snapshot Testing Concept</h3>
|
|
<p>Test view structure (conceptual, requires snapshot library):</p>
|
|
<pre><code class="lang-swift">@Test
|
|
func testUserProfileView() {
|
|
let user = User(id: UUID(), name: "Test User", email: "[email protected]")
|
|
let view = UserProfileView(user: user)
|
|
|
|
// With snapshot testing library:
|
|
// assertSnapshot(matching: view, as: .image)
|
|
}</code></pre>
|
|
<h3>Testing View Logic</h3>
|
|
<p>Test extracted view logic:</p>
|
|
<pre><code class="lang-swift">struct TaskListView: View {
|
|
let tasks: [Task]
|
|
|
|
// Extract filtering logic
|
|
func filteredTasks(searchText: String) -> [Task] {
|
|
guard !searchText.isEmpty else { return tasks }
|
|
|
|
return tasks.filter { task in
|
|
task.title.localizedStandardContains(searchText)
|
|
}
|
|
}
|
|
|
|
var body: some View {
|
|
List(tasks) { task in
|
|
Text(task.title)
|
|
}
|
|
}
|
|
}
|
|
|
|
@Test
|
|
func testTaskFiltering() {
|
|
let tasks = [
|
|
Task(title: "Buy milk"),
|
|
Task(title: "Write code"),
|
|
Task(title: "Buy groceries")
|
|
]
|
|
|
|
let view = TaskListView(tasks: tasks)
|
|
|
|
let filtered = view.filteredTasks(searchText: "buy")
|
|
#expect(filtered.count == 2)
|
|
#expect(filtered.allSatisfy { $0.title.lowercased().contains("buy") })
|
|
}</code></pre>
|
|
<h2>Testing Network Code</h2>
|
|
<h3>Mock Network Service</h3>
|
|
<p>Create testable network layer:</p>
|
|
<pre><code class="lang-swift">protocol NetworkServiceProtocol {
|
|
func fetch<T: Decodable>(url: URL, as type: T.Type) async throws -> T
|
|
}
|
|
|
|
final class MockNetworkService: NetworkServiceProtocol {
|
|
var dataToReturn: Data?
|
|
var errorToThrow: Error?
|
|
|
|
func fetch<T: Decodable>(url: URL, as type: T.Type) async throws -> T {
|
|
if let error = errorToThrow {
|
|
throw error
|
|
}
|
|
|
|
guard let data = dataToReturn else {
|
|
throw NetworkError.noData
|
|
}
|
|
|
|
return try JSONDecoder().decode(T.self, from: data)
|
|
}
|
|
}
|
|
|
|
@Test
|
|
func testNetworkSuccess() async throws {
|
|
let mockService = MockNetworkService()
|
|
let userData = """
|
|
{"id": "123", "name": "Test User", "email": "[email protected]"}
|
|
""".data(using: .utf8)!
|
|
|
|
mockService.dataToReturn = userData
|
|
|
|
let user = try await mockService.fetch(
|
|
url: URL(string: "https://api.example.com/user")!,
|
|
as: User.self
|
|
)
|
|
|
|
#expect(user.name == "Test User")
|
|
}
|
|
|
|
@Test
|
|
func testNetworkError() async {
|
|
let mockService = MockNetworkService()
|
|
mockService.errorToThrow = NetworkError.serverError
|
|
|
|
await #expect(throws: NetworkError.self) {
|
|
try await mockService.fetch(
|
|
url: URL(string: "https://api.example.com/user")!,
|
|
as: User.self
|
|
)
|
|
}
|
|
}</code></pre>
|
|
<h3>Testing with Mock Data</h3>
|
|
<p>Use mock responses:</p>
|
|
<pre><code class="lang-swift">struct MockData {
|
|
static let validUser = """
|
|
{
|
|
"id": "550e8400-e29b-41d4-a716-446655440000",
|
|
"name": "Test User",
|
|
"email": "[email protected]",
|
|
"createdAt": "2024-01-01T00:00:00Z"
|
|
}
|
|
""".data(using: .utf8)!
|
|
|
|
static let usersList = """
|
|
{
|
|
"users": [
|
|
{"id": "550e8400-e29b-41d4-a716-446655440000", "name": "User 1", "email": "[email protected]"},
|
|
{"id": "550e8400-e29b-41d4-a716-446655440001", "name": "User 2", "email": "[email protected]"}
|
|
],
|
|
"total": 2
|
|
}
|
|
""".data(using: .utf8)!
|
|
|
|
static let errorResponse = """
|
|
{
|
|
"error": "Not found",
|
|
"code": 404
|
|
}
|
|
""".data(using: .utf8)!
|
|
}
|
|
|
|
@Test
|
|
func testUserDecoding() throws {
|
|
let user = try JSONDecoder().decode(User.self, from: MockData.validUser)
|
|
|
|
#expect(user.name == "Test User")
|
|
#expect(user.email == "[email protected]")
|
|
}</code></pre>
|
|
<h2>Testing SwiftData Models</h2>
|
|
<h3>In-Memory Persistence</h3>
|
|
<p>Test models with in-memory store:</p>
|
|
<pre><code class="lang-swift">@Test
|
|
func testModelPersistence() async throws {
|
|
let config = ModelConfiguration(isStoredInMemoryOnly: true)
|
|
let container = try ModelContainer(
|
|
for: Task.self,
|
|
configurations: config
|
|
)
|
|
|
|
let context = ModelContext(container)
|
|
|
|
// Create
|
|
let task = Task(title: "Test Task")
|
|
context.insert(task)
|
|
try context.save()
|
|
|
|
// Fetch
|
|
let descriptor = FetchDescriptor<Task>()
|
|
let tasks = try context.fetch(descriptor)
|
|
|
|
#expect(tasks.count == 1)
|
|
#expect(tasks.first?.title == "Test Task")
|
|
|
|
// Update
|
|
task.isCompleted = true
|
|
try context.save()
|
|
|
|
#expect(task.isCompleted == true)
|
|
|
|
// Delete
|
|
context.delete(task)
|
|
try context.save()
|
|
|
|
let afterDelete = try context.fetch(descriptor)
|
|
#expect(afterDelete.isEmpty)
|
|
}
|
|
|
|
@Test
|
|
func testModelRelationships() throws {
|
|
let config = ModelConfiguration(isStoredInMemoryOnly: true)
|
|
let container = try ModelContainer(
|
|
for: [Project.self, Task.self],
|
|
configurations: config
|
|
)
|
|
|
|
let context = ModelContext(container)
|
|
|
|
let project = Project(name: "Test Project")
|
|
context.insert(project)
|
|
|
|
let task1 = Task(title: "Task 1", project: project)
|
|
let task2 = Task(title: "Task 2", project: project)
|
|
|
|
context.insert(task1)
|
|
context.insert(task2)
|
|
|
|
try context.save()
|
|
|
|
#expect(project.tasks.count == 2)
|
|
#expect(task1.project?.name == "Test Project")
|
|
}</code></pre>
|
|
<h2>Test Organization</h2>
|
|
<h3>Test Suites</h3>
|
|
<p>Group related tests:</p>
|
|
<pre><code class="lang-swift">@Suite("User Management Tests")
|
|
struct UserTests {
|
|
@Test("Create user")
|
|
func createUser() async throws {
|
|
// Test implementation
|
|
}
|
|
|
|
@Test("Update user")
|
|
func updateUser() async throws {
|
|
// Test implementation
|
|
}
|
|
|
|
@Test("Delete user")
|
|
func deleteUser() async throws {
|
|
// Test implementation
|
|
}
|
|
}
|
|
|
|
@Suite("Authentication Tests", .tags(.auth))
|
|
struct AuthTests {
|
|
@Test
|
|
func login() async throws {
|
|
// Test implementation
|
|
}
|
|
|
|
@Test
|
|
func logout() async throws {
|
|
// Test implementation
|
|
}
|
|
}</code></pre>
|
|
<h3>Tags for Organization</h3>
|
|
<p>Use tags to categorize tests:</p>
|
|
<pre><code class="lang-swift">extension Tag {
|
|
@Tag static var unit: Self
|
|
@Tag static var integration: Self
|
|
@Tag static var ui: Self
|
|
@Tag static var network: Self
|
|
@Tag static var slow: Self
|
|
}
|
|
|
|
@Test(.tags(.unit, .network))
|
|
func testAPIClient() async throws {
|
|
// Network unit test
|
|
}
|
|
|
|
@Test(.tags(.integration, .slow))
|
|
func testFullUserFlow() async throws {
|
|
// Integration test
|
|
}</code></pre>
|
|
<h3>Setup and Teardown</h3>
|
|
<p>Initialize test state:</p>
|
|
<pre><code class="lang-swift">@Suite("Database Tests")
|
|
struct DatabaseTests {
|
|
var container: ModelContainer
|
|
|
|
init() throws {
|
|
let config = ModelConfiguration(isStoredInMemoryOnly: true)
|
|
container = try ModelContainer(
|
|
for: Task.self,
|
|
configurations: config
|
|
)
|
|
}
|
|
|
|
@Test
|
|
func testOperation1() throws {
|
|
let context = ModelContext(container)
|
|
// Test using context
|
|
}
|
|
|
|
@Test
|
|
func testOperation2() throws {
|
|
let context = ModelContext(container)
|
|
// Test using context
|
|
}
|
|
}</code></pre>
|
|
<h2>Testing Best Practices</h2>
|
|
<h3>AAA Pattern</h3>
|
|
<p>Use Arrange-Act-Assert:</p>
|
|
<pre><code class="lang-swift">@Test
|
|
func testUserCreation() async throws {
|
|
// Arrange
|
|
let mockService = MockUserService()
|
|
let viewModel = UserViewModel(service: mockService)
|
|
|
|
// Act
|
|
await viewModel.createUser(name: "Test", email: "[email protected]")
|
|
|
|
// Assert
|
|
#expect(viewModel.user?.name == "Test")
|
|
#expect(viewModel.user?.email == "[email protected]")
|
|
}</code></pre>
|
|
<h3>Test Isolation</h3>
|
|
<p>Keep tests independent:</p>
|
|
<pre><code class="lang-swift">@Suite
|
|
struct IsolatedTests {
|
|
@Test
|
|
func test1() async throws {
|
|
// Create own test data
|
|
let data = TestData()
|
|
// Test with data
|
|
}
|
|
|
|
@Test
|
|
func test2() async throws {
|
|
// Create own test data (don't reuse from test1)
|
|
let data = TestData()
|
|
// Test with data
|
|
}
|
|
}</code></pre>
|
|
<h3>Descriptive Test Names</h3>
|
|
<p>Write clear test names:</p>
|
|
<pre><code class="lang-swift">// ❌ BAD
|
|
@Test func test1() { }
|
|
@Test func testUser() { }
|
|
|
|
// ✅ GOOD
|
|
@Test("User is created with valid email")
|
|
func userCreationWithValidEmail() { }
|
|
|
|
@Test("Login fails with invalid credentials")
|
|
func loginFailureWithInvalidCredentials() { }</code></pre>
|
|
<h2>Anti-Patterns to Avoid</h2>
|
|
<p><strong>DON'T test implementation details:</strong></p>
|
|
<pre><code class="lang-swift">// ❌ BAD - Testing private implementation
|
|
@Test
|
|
func testInternalCache() {
|
|
// Don't test internal caching mechanism
|
|
}
|
|
|
|
// ✅ GOOD - Test public behavior
|
|
@Test
|
|
func testDataFetchingReturnsCorrectData() async throws {
|
|
let data = try await service.fetchData()
|
|
#expect(data.count > 0)
|
|
}</code></pre>
|
|
<p><strong>DON'T write dependent tests:</strong></p>
|
|
<pre><code class="lang-swift">// ❌ BAD - Test depends on order
|
|
var sharedState: User?
|
|
|
|
@Test
|
|
func test1() {
|
|
sharedState = User(name: "Test")
|
|
}
|
|
|
|
@Test
|
|
func test2() {
|
|
#expect(sharedState?.name == "Test") // Fragile!
|
|
}
|
|
|
|
// ✅ GOOD - Independent tests
|
|
@Test
|
|
func test1() {
|
|
let user = User(name: "Test")
|
|
#expect(user.name == "Test")
|
|
}
|
|
|
|
@Test
|
|
func test2() {
|
|
let user = User(name: "Another")
|
|
#expect(user.name == "Another")
|
|
}</code></pre>
|
|
<p><strong>DON'T ignore async context:</strong></p>
|
|
<pre><code class="lang-swift">// ❌ BAD - Not awaiting async work
|
|
@Test
|
|
func badAsyncTest() {
|
|
Task {
|
|
let user = try await fetchUser()
|
|
#expect(user != nil) // May not execute!
|
|
}
|
|
}
|
|
|
|
// ✅ GOOD
|
|
@Test
|
|
func goodAsyncTest() async throws {
|
|
let user = try await fetchUser()
|
|
#expect(user != nil)
|
|
}</code></pre>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><strong>swiftui-architecture.md</strong> - Testing view models</li><li><strong>swift-concurrency.md</strong> - Testing actors and async code</li><li><strong>swiftdata-persistence.md</strong> - Testing data models</li><li><strong>ios-networking.md</strong> - Mocking network services</li><li><strong>swiftui-navigation.md</strong> - Testing navigation flows</li></ul>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/ios-testing.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |