XCTest Test Data: Seeded JSON Fixtures for Swift Testing and XCTest
XCTest test data for a Swift app usually means a decoder test and a
networking test, each fed a JSON payload that someone pasted into the
test target once and never touched again. This post replaces that with
one generated fixture. A seeded template produces a table of API
payloads, valid and deliberately broken, each tagged with the outcome
it should produce. Your tests load the file from the test bundle,
decode it with Codable, and run every row as its own case: in Swift
Testing with @Test(arguments:), in XCTest with a loop, and through
URLSession with a URLProtocol stub. When a row fails, the seed in
its name rebuilds the exact file.
JsonFabrica is the generator, and it's only a JSON-over-HTTP API. There's no Swift package, Xcode plugin or XCTest extension. A short shell script calls the API and writes the result into the test target, and the tests read that committed file. Test runs never touch the network.
The package code below was built and run with swift test on Swift
6.4.2 for Linux, in Swift 6 language mode, with Swift Testing and
XCTest in the same test target. The Bundle(for:) branch for Xcode
projects was only compiled and run as a standalone swiftc file on
Linux, outside SwiftPM. Nothing was built or run in Xcode or on an
Apple OS; Apple-platform differences are called out where they matter.
The Codable model under test
The example is a booking app that fetches appointments from its API.
One Appointment is a plain Codable struct, and a single static
function does all the decoding and checking, so the app and the tests
go through the same code:
// Sources/Appointments/Appointment.swift
import Foundation
public struct Appointment: Codable, Equatable, Sendable {
public enum Kind: String, Codable, Sendable {
case inPerson = "in-person", video, phone
}
public let id: String
public let client: String
public let email: String
public let startsAt: Date
public let durationMinutes: Int
public let kind: Kind
public static let allowedDuration = 15...180
}
public enum AppointmentError: Error, Equatable {
case durationOutOfRange(Int)
}
extension Appointment {
/// Decodes and checks one API payload. The app and the tests
/// both go through here.
public static func decode(_ data: Data) throws -> Appointment {
let appointment = try JSONDecoder.api.decode(Self.self, from: data)
guard allowedDuration.contains(appointment.durationMinutes) else {
throw AppointmentError.durationOutOfRange(
appointment.durationMinutes)
}
return appointment
}
}
extension JSONDecoder {
/// Configured the way the API encodes its responses.
public static var api: JSONDecoder {
let decoder = JSONDecoder()
// Accepts "…T11:54:58Z" and "…T11:54:58.732Z" alike, on old and
// new Foundation. Anything else is a decoding error.
decoder.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)
let styles: [Date.ISO8601FormatStyle] = [
.init(includingFractionalSeconds: true), .init(),
]
for style in styles {
if let date = try? style.parse(string) { return date }
}
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Not an ISO 8601 date: \(string)")
}
return decoder
}
}
A payload can be rejected at two levels. JSONDecoder throws a
DecodingError when the JSON doesn't fit the type: a missing key, an
unknown kind, a date it can't parse. decode(_:) then throws
AppointmentError.durationOutOfRange for a payload that decodes fine
but breaks a business rule. The fixture plants rows for both.
Choosing a JSONDecoder dateDecodingStrategy
Generated dates are strings, and JSONDecoder has to be told how to
read them. The strategies, and what each does with a date like
2026-06-18T11:54:58Z:
.deferredToDate, the default, decodesDateas a number of seconds since 1 January 2001. Give it an ISO 8601 string and you gettypeMismatch: "Expected to decode Double but found a string instead." The exact wording varies by Foundation version..iso8601reads RFC 3339 timestamps with a time zone, such asZor+02:00. A string without one, like2026-06-18T11:54:58, fails withdataCorrupted: "Expected date string to be ISO8601-formatted." Foundation from Swift 6.2 on accepts2026-06-18T11:54:58.732Z(the 6.4.2 Linux toolchain used here did). Earlier releases reject it with that same error, and on Apple platforms the OS version decides which Foundation you get..secondsSince1970and.millisecondsSince1970read Unix timestamps, for APIs that send numbers..formatted(_:)takes aDateFormatterwith a fixed format, and.customtakes a closure that decodes the value itself.
The decoder above uses .custom to try
Date.ISO8601FormatStyle(includingFractionalSeconds: true) first and
the plain style second. That pins the behavior: with or without
milliseconds, any Foundation version, the same strings decode and the
same strings fail. If your API never sends milliseconds, .iso8601 on
its own is fine, but drop the fractional-seconds row, since its
outcome would then depend on the Foundation version.
A template that generates Swift test data JSON with planted edge rows
The template generates the whole fixture: a list of cases, each with a name, an expected outcome and the payload the API would send. Rows 1 to 8 are planted cases, chosen by loop index. Every row after that is an ordinary valid appointment.
{
"cases": [
<for(i, 1, getParam('cases', 12))><if(getVar('i') > 1)>,<endIf>
<setVar('start', getRandomDate('2026-01-05', '2026-12-18'))>
{
"id": "case-<appendBefore('0', getVar('i'), 2)>",
"name": <if(getVar('i') == 1)>"no-timezone"
<elseIf(getVar('i') == 2)>"fractional-seconds"
<elseIf(getVar('i') == 3)>"missing-email"
<elseIf(getVar('i') == 4)>"unknown-kind"
<elseIf(getVar('i') == 5)>"shortest"
<elseIf(getVar('i') == 6)>"too-short"
<elseIf(getVar('i') == 7)>"longest"
<elseIf(getVar('i') == 8)>"too-long"
<else>"valid"<endIf>,
"expect": <if(getVar('i') == 1 || getVar('i') == 4)>"dataCorrupted"
<elseIf(getVar('i') == 3)>"keyNotFound"
<elseIf(getVar('i') == 6 || getVar('i') == 8)>"durationOutOfRange"
<else>"ok"<endIf>,
"payload": {
"id": "apt-<formatDate(getVar('start'), 'YYYYMMDD-HHmm')>",
"client": "<getRandomFullName()>",
<if(getVar('i') != 3)>"email": "<getRandomEmail('example.com')>",<endIf>
"startsAt": <if(getVar('i') == 1)>
"<formatDate(getVar('start'), 'YYYY-MM-DDTHH:mm:00')>"
<elseIf(getVar('i') == 2)>"<getVar('start')>"
<else>"<formatDate(getVar('start'), 'YYYY-MM-DDTHH:mm:00Z')>"<endIf>,
"durationMinutes": <if(getVar('i') == 5)>15
<elseIf(getVar('i') == 6)>10
<elseIf(getVar('i') == 7)>180
<elseIf(getVar('i') == 8)>181
<else><getRandomElement(30, 45, 60, 90)><endIf>,
"kind": <if(getVar('i') == 4)>"house-call"
<else>"<getRandomElement('in-person', 'video', 'phone')>"<endIf>
}
}<end_for>
]
}
What each part does:
startis the only variable, because two fields read it. Each row draws one timestamp withgetRandomDateand stores it withsetVar. The payload'sidand itsstartsAtare both formatted from it withformatDate, so an appointment's id always matches its start time. Everything else is inline.- Each planted row breaks one thing. Case 1 drops the time zone.
Case 3 leaves out the
emailkey entirely, soJSONDecoderthrowskeyNotFoundrather than complaining about a value. Case 4 sends akindtheKindenum has no case for. The other fields in each row are ordinary valid values, so the row can only fail for one reason. - Case 2 keeps the raw milliseconds on purpose.
getRandomDatereturns a full ISO 8601 timestamp with milliseconds, like2026-06-18T11:54:58.732Z. Every other row runs it throughformatDateto get a timestamp without milliseconds (seconds zeroed, matching the minute-levelid). Case 2 prints it as is, and expectsok, which pins the decoder's fractional-seconds behavior described above. - Four rows sit on the duration limits. Cases 5 and 7 send 15 and
180, the limits themselves, and should pass. Cases 6 and 8 send 10
and 181 and should fail. An off-by-one in
allowedDurationbreaks one of them. - Every row carries its expected outcome.
expectcomes from the same loop index as the defect, so the data and the expectation can't drift apart. Its values are the names of a Swift enum the tests decode it into.
Template expressions support comparisons (==, !=, <, <=, >,
>=) and &&/||, but no arithmetic, which is why the planted rows
are picked by index rather than computed. for bounds are inclusive,
the loop bound reads the cases param inline with
getParam, and the
<if(getVar('i') > 1)>,<endIf> guard puts a comma before every item
except the first. The control flow docs cover
for and if/elseIf/else. Keep cases at 8 or more, or some
planted rows won't be generated.
Rendered with seed 1117 and the default 12 cases, the fixture starts
like this, trimmed to cases 2 and 3:
{
"seed": 1117,
"cases": [
{
"id": "case-02",
"name": "fractional-seconds",
"expect": "ok",
"payload": {
"id": "apt-20260618-1154",
"client": "Nova Cunningham",
"email": "[email protected]",
"startsAt": "2026-06-18T11:54:58.732Z",
"durationMinutes": 90,
"kind": "video"
}
},
{
"id": "case-03",
"name": "missing-email",
"expect": "keyNotFound",
"payload": {
"id": "apt-20260707-1705",
"client": "Ira Yorkworth",
"startsAt": "2026-07-07T17:05:00Z",
"durationMinutes": 45,
"kind": "in-person"
}
}
]
}
The seed key isn't part of the template. The regen script adds it
from the API response, so the file records how to rebuild itself.
Regenerating the JSON fixture from a seed
The regen script is the only code that talks to JsonFabrica. It sends
the raw template to
POST /v1/templates/generate, which
renders a template without saving it, and writes the result into the
test target:
#!/usr/bin/env bash
# Regenerates the appointments fixture from scripts/appointments.tmpl.
# scripts/regen-fixtures.sh # pinned seed 1117: no diff
# scripts/regen-fixtures.sh 4711 # rebuild the file for a logged seed
# scripts/regen-fixtures.sh random # let the API pick a seed
# Review the diff and commit. Tests never call the API.
set -euo pipefail
cd "$(dirname "$0")/.."
seed=${1:-1117}
out=Tests/AppointmentsTests/Fixtures/appointments.json
request=$(jq -n --rawfile body scripts/appointments.tmpl --arg seed "$seed" '
{body: $body, params: {cases: 12}}
+ if $seed == "random" then {} else {seed: ($seed | tonumber)} end')
# Errors come back as {"error": {"code", "message", "details"}}.
response=$(curl -sS --fail-with-body \
https://api.jsonfabrica.com/v1/templates/generate \
-H "Authorization: Bearer $JSONFABRICA_API_KEY" \
-H "Content-Type: application/json" \
-d "$request") || { echo "$response" >&2; exit 1; }
# Keep the seed in the file; drop meta.generatedAt, which changes every call.
jq '{seed: .meta.seed} + .data' <<<"$response" > "$out"
echo "seed $(jq .seed "$out"): $(jq '.cases | length' "$out") cases"
It needs curl and jq, which most Macs and CI images already have
or can install in one line. Things worth knowing about the request and
response:
- The response is
{ data, meta }.datais the generated document.meta.seedis the seed that was used, either the one you sent or, withrandom, the one the API picked. - Same template, seed and params give the same file. Running the
script with the pinned seed produces no diff. Editing the template or
changing
casesshifts the random draws, so commit the template and the fixture together. - A failed request leaves the fixture alone. The script only
writes the file after
curlsucceeds, and prints the API's error body otherwise. - The template lives in
scripts/, not in the test target, so it never gets copied into the test bundle.
JSONFABRICA_API_KEY=... scripts/regen-fixtures.sh # seed 1117: 12 cases
swift test
git add scripts/appointments.tmpl Tests/AppointmentsTests/Fixtures
If you'd rather stay in Swift, the same request is a few lines of
URLSession in a script or a small executable target. What matters is
that the generated file is committed and the tests read the file.
Loading XCTest test data from the test bundle
The fixture has to end up inside the test bundle, and the tests have to find it there. How depends on whether the tests live in a Swift package or an Xcode project.
Swift packages: test resources and Bundle.module
In a package, declare the fixture folder as a resource of the test target:
// swift-tools-version: 6.0
// Package.swift
import PackageDescription
let package = Package(
name: "Appointments",
platforms: [.macOS(.v13), .iOS(.v16)],
targets: [
.target(name: "Appointments"),
.testTarget(
name: "AppointmentsTests",
dependencies: ["Appointments"],
resources: [.process("Fixtures")]
),
]
)
With the file at Tests/AppointmentsTests/Fixtures/appointments.json:
- Declaring resources is what creates
Bundle.module. SwiftPM generates theBundle.moduleaccessor only for targets that list resources, and it points at the bundle those resources are copied into. Without theresources:line,Bundle.moduledoesn't compile. .processcopies the folder's files to the bundle root. A JSON file needs no processing, so it's copied as is, and the lookup isurl(forResource: "appointments", withExtension: "json")with no subdirectory..copy("Fixtures")keeps the folder instead, and the lookup then needssubdirectory: "Fixtures".Bundle.mainis not the test bundle. In a test run it points at the test runner or the host app, so fixtures looked up there come backnil.
The .macOS(.v13) and .iOS(.v16) minimums are there for
URL.appending(path:) in the client code later on.
Xcode test targets: Bundle(for:)
A test target in an Xcode app or framework project gets no
Bundle.module. Select the JSON file, tick the test target under
Target Membership in the File inspector, and in a project that
uses classic groups, check that it shows up in the target's Copy
Bundle Resources build phase. Then find the
bundle through a class compiled into that target:
/// The bundle that holds the test fixtures.
private final class FixtureBundleToken {}
extension Bundle {
static var fixtures: Bundle {
#if SWIFT_PACKAGE
return .module
#else
return Bundle(for: FixtureBundleToken.self)
#endif
}
}
Bundle(for:) returns the bundle a class was loaded from, so an empty
class in the test target leads to the .xctest bundle. Swift Testing
suites are usually structs, which is why the token is a separate
class. SWIFT_PACKAGE is set when SwiftPM builds the code, so the same
file works in both setups. Files added to an Xcode group are usually
copied flat into the bundle root too, so the lookup without a
subdirectory works there as well.
Decoding Codable test fixtures
The loader reads the file once per call and returns one value per row:
// Tests/AppointmentsTests/AppointmentFixture.swift
import Foundation
import Testing
@testable import Appointments
enum Outcome: String, Decodable, Sendable {
case ok, keyNotFound, dataCorrupted, durationOutOfRange
}
struct AppointmentCase: Decodable, Sendable, Identifiable {
let id: String
let name: String
let expect: Outcome
var seed = 0
var payload = Data() // the row's raw JSON, filled in by load()
enum CodingKeys: String, CodingKey { case id, name, expect }
}
extension AppointmentCase: CustomTestStringConvertible {
var testDescription: String { "\(id) \(name) (seed \(seed))" }
}
enum AppointmentFixture {
private struct File: Decodable {
let seed: Int
let cases: [AppointmentCase]
}
static func load() throws -> [AppointmentCase] {
guard let url = Bundle.fixtures.url(
forResource: "appointments", withExtension: "json"
) else { throw CocoaError(.fileNoSuchFile) }
let data = try Data(contentsOf: url)
let file = try JSONDecoder().decode(File.self, from: data)
// Keep each payload as raw bytes, so tests decode it the way
// the app decodes a response body.
let json = try JSONSerialization.jsonObject(with: data)
let rows = (json as? [String: Any])?["cases"] as? [[String: Any]]
return try zip(file.cases, rows ?? []).map { row, raw in
var row = row
row.seed = file.seed
row.payload = try JSONSerialization.data(
withJSONObject: raw["payload"] ?? [:])
return row
}
}
}
extension Outcome {
/// Runs the app's decode-and-validate path and names the result.
/// Errors the fixture has no name for are rethrown.
init(_ work: () async throws -> Appointment) async throws {
do {
_ = try await work()
self = .ok
} catch DecodingError.keyNotFound {
self = .keyNotFound
} catch DecodingError.dataCorrupted {
self = .dataCorrupted
} catch AppointmentError.durationOutOfRange {
self = .durationOutOfRange
}
}
}
Plus the Bundle.fixtures extension from the previous section. How
the pieces fit:
- Codable reads the row metadata, but not the payload. The fixture
is full of payloads built to fail decoding. Decoding them as
Appointmentinside the fixture's own decode would throw on case 1 and lose the whole file. SoCodingKeysleavespayloadout, and the loader re-serializes each row's payload toDatawithJSONSerialization. Each test then hands raw bytes toAppointment.decode(_:), exactly like a response body. expectdecodes straight intoOutcome. The template's strings are the enum's raw values. A typo in the template fails the load with adataCorruptederror instead of quietly matching nothing.Outcome.initturns a result into a name. It runs the app's code and maps the three expected kinds of failure to cases. Any other error, say atypeMismatchfrom a future template change, isn't caught and fails the test with the real error.- Every row carries the seed.
testDescriptionputs it into each test case's name, which matters later when a row fails in CI.
Swift Testing parameterized tests over fixture rows
With the loader in place, the Swift Testing version is one test function:
// Tests/AppointmentsTests/AppointmentDecodingTests.swift
import Testing
@testable import Appointments
@Suite("Appointment decoding")
struct AppointmentDecodingTests {
@Test(arguments: try AppointmentFixture.load())
func decodesFixtureRow(_ row: AppointmentCase) async throws {
let outcome = try await Outcome { try Appointment.decode(row.payload) }
#expect(outcome == row.expect)
}
}
What @Test(arguments:) does with it:
- Each row is its own test case. Swift Testing calls
decodesFixtureRowonce per element and reports each call separately, so one bad row doesn't hide the others. Test cases run in parallel by default, which is fine here: each one only reads its own row. - The arguments expression can throw. If the fixture is missing or malformed, the test records the error as an issue and fails, instead of passing with zero cases.
- Arguments must be
Sendable.AppointmentCaseholds only strings, an enum, anIntandData, so it conforms without extra work. CustomTestStringConvertiblenames the cases. Without it, the output would print the whole struct. With it, each case shows up ascase-03 missing-email (seed 1117).Identifiablegives each case a stable identity. Swift Testing can rerun a single argument when it isEncodable, orRawRepresentableorIdentifiablewith an encodable raw value or ID, and Xcode 16 and later let you rerun one from the test report. From the command line,swift test --filter decodesFixtureRowreruns the function, and all 12 rows take a few milliseconds.
The shape is the same in other languages: table-driven subtests in
the Go version, xUnit theories in the
C# and .NET post. In Swift Testing,
the table is the arguments collection.
The same table-driven test in XCTest
XCTest has no parameterized tests, so the XCTest version loops over the rows and puts the row name into every assertion's message:
// Tests/AppointmentsTests/AppointmentDecodingXCTests.swift
import XCTest
@testable import Appointments
final class AppointmentDecodingXCTests: XCTestCase {
func testEveryFixtureRow() async throws {
for row in try AppointmentFixture.load() {
let outcome = try await Outcome {
try Appointment.decode(row.payload)
}
XCTAssertEqual(outcome, row.expect, row.testDescription)
}
}
}
It reuses the same loader, Outcome and fixture. The differences:
- It's one test, not twelve. XCTest reports
testEveryFixtureRowas a single pass or fail.continueAfterFailureistrueby default, so a failing row records a failure and the loop moves on to the next one, and every bad row shows up in one run. - The message is the row's name.
XCTAssertEqualappends it to the failure, so the seed and case id are in the log next to the values. - An unexpected error ends the loop. If
Outcome.initrethrows, thetryexits the test method, and later rows don't run. Swift Testing doesn't have that problem, since each row is a separate call.
Both styles can live in the same test target. swift test runs the
XCTest tests and then the Swift Testing tests, and Xcode runs both in
one test plan, which helps when a suite is moving to Swift Testing a
file at a time.
Mocking URLSession with a URLProtocol stub
The same rows can test the networking layer. The client fetches one appointment and decodes it with the shared function:
// Sources/Appointments/AppointmentsClient.swift
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking // URLSession on Linux
#endif
public struct AppointmentsClient: Sendable {
let baseURL: URL
let session: URLSession
public init(baseURL: URL, session: URLSession = .shared) {
self.baseURL = baseURL
self.session = session
}
public func appointment(id: String) async throws -> Appointment {
let url = baseURL.appending(path: "appointments/\(id)")
let (data, response) = try await session.data(from: url)
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
throw URLError(.badServerResponse)
}
return try Appointment.decode(data)
}
}
A URLProtocol subclass sits under URLSession and answers requests
instead of the network. This one serves each fixture row at
/appointments/<case id>:
// Tests/AppointmentsTests/AppointmentsClientTests.swift
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
import Testing
@testable import Appointments
/// Answers GET /appointments/<case id> with that row's payload.
final class FixtureURLProtocol: URLProtocol {
static let payloads: [String: Data] = {
let rows = (try? AppointmentFixture.load()) ?? []
return Dictionary(
uniqueKeysWithValues: rows.map { ($0.id, $0.payload) })
}()
override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(
for request: URLRequest
) -> URLRequest { request }
override func startLoading() {
guard let url = request.url else { return }
let body = Self.payloads[url.lastPathComponent]
let response = HTTPURLResponse(
url: url, statusCode: body == nil ? 404 : 200,
httpVersion: "HTTP/1.1",
headerFields: ["Content-Type": "application/json"])!
client?.urlProtocol(
self, didReceive: response, cacheStoragePolicy: .notAllowed)
client?.urlProtocol(self, didLoad: body ?? Data())
client?.urlProtocolDidFinishLoading(self)
}
override func stopLoading() {}
}
@Suite("AppointmentsClient")
struct AppointmentsClientTests {
let client: AppointmentsClient = {
let config = URLSessionConfiguration.ephemeral
config.protocolClasses = [FixtureURLProtocol.self]
return AppointmentsClient(
baseURL: URL(string: "https://api.example.test")!,
session: URLSession(configuration: config))
}()
@Test(arguments: try AppointmentFixture.load())
func fetchesFixtureRow(_ row: AppointmentCase) async throws {
let outcome = try await Outcome {
try await client.appointment(id: row.id)
}
#expect(outcome == row.expect)
}
}
How the stub works:
protocolClassesputs the stub in front. A session built from this configuration asksFixtureURLProtocol.canInit(with:)first. It returnstruefor everything, so no request reaches the network, andapi.example.testnever has to exist. Only this session is affected;URLSession.sharedand other tests' sessions are not.startLoadingplays the server. It sends a response, the body and a finished signal toclient, the objectURLSessiongives every protocol instance. An unknown id gets a 404 with an empty body.- There's no shared mutable state. A common stub pattern stores a
per-test request handler in a static
var, which races once Swift Testing runs cases in parallel. Here the routes are astatic letbuilt from the fixture, so every case reads the same immutable dictionary and picks its own payload by URL. - The client code runs for real. The status check, the decoder and the duration rule all run against generated bytes, and the expected outcome per row is the same as in the decoding test.
- Linux needs
FoundationNetworking. On Linux,URLSessionandURLProtocollive in that module, so both files import it when it's available. On Apple platforms the#ifis skipped.
The same idea, generated payloads instead of hand-written ones, works for frontend mocks and mock servers; the mock API response data post covers that side.
Reproducing a failing row from its seed
Here's what a failure looks like. Change allowedDuration to
15..<180 and the longest row fails in both test styles. This is the
real output, wrapped to fit and trimmed to the two decoding tests,
with the XCTest file path shortened to .... Its line numbers count
from the test files without the path comment shown in the listings
above. A full run also fails case-07 in
AppointmentsClientTests.fetchesFixtureRow, since the client goes
through the same Appointment.decode. The last three lines are
XCTest (Linux output); on macOS the test is named
-[AppointmentsTests.AppointmentDecodingXCTests testEveryFixtureRow]:
✘ Test decodesFixtureRow(_:) recorded an issue with 1 argument
row → case-07 longest (seed 1117) at AppointmentDecodingTests.swift:9:9:
Expectation failed: outcome == row.expect
↳ outcome == row.expect → false
↳ outcome → .durationOutOfRange
↳ row.expect → .ok
✘ Test decodesFixtureRow(_:) with 12 test cases failed after 0.002
seconds with 1 issue.
.../AppointmentDecodingXCTests.swift:10: error:
AppointmentDecodingXCTests.testEveryFixtureRow : XCTAssertEqual failed:
("durationOutOfRange") is not equal to ("ok") - case-07 longest (seed 1117)
Both name the row and the seed. With the pinned seed that's all you need, since the committed file is the one that failed.
The seed starts to matter when CI tries new data. A scheduled job can regenerate the fixture with a fresh seed before testing, which varies the random parts of each row: names, emails, dates, kinds and the durations of the valid rows. The planted rows keep their defects and expected outcomes at every seed.
scripts/regen-fixtures.sh random # prints "seed 1621203832: 12 cases"
swift test
The job doesn't commit anything. The regen script prints meta.seed
before the tests start, and every test case name repeats it, so the
seed is next to the failure in the log. To reproduce locally, rebuild
that exact file and rerun the test:
scripts/regen-fixtures.sh 1621203832
swift test --filter decodesFixtureRow
The same seed, template and params give a byte-identical file, so the local run sees exactly the data CI saw. The deterministic test data post goes deeper into seed-based replay. Once you've fixed the bug, either commit that seed's file or add the input that broke things as a new planted row, then run the script with no arguments to put the pinned fixture back.
FAQ
How do I load a JSON file in a Swift unit test?
Add the file to the test target as a resource and ask the test bundle
for its URL. In a Swift package, list the fixture folder in the test
target's resources with .process and call
Bundle.module.url(forResource:withExtension:). In an Xcode project
test target, tick the test target under Target Membership and use
Bundle(for:) with a class defined in the test target. Then read the
file with Data(contentsOf:) and decode it with JSONDecoder.
Why is Bundle.module not available in my test target?
SwiftPM only generates Bundle.module for a target that declares
resources in Package.swift, so add a resources entry to the test
target. Test targets in an Xcode app or framework project don't get it
at all; there, use Bundle(for:) with a class that lives in the test
target. Bundle.main is the wrong bundle in tests, because it points
at the test runner or host app rather than the test bundle.
How do you write a parameterized test in Swift Testing?
Pass a collection to the @Test macro's arguments parameter and give
the test function a matching parameter, for example
@Test(arguments: rows) func check(_ row: Row). Swift Testing runs the
function once per element as a separate test case, in parallel by
default, and reports failures per argument. The arguments must be
Sendable, and conforming the argument type to
CustomTestStringConvertible controls how each case is named in the
output.
Why does JSONDecoder fail to decode an ISO 8601 date string?
JSONDecoder's default dateDecodingStrategy, deferredToDate,
expects a number, so an ISO 8601 string fails with a typeMismatch
error. Set the strategy to iso8601 for strings like
2026-06-18T11:54:58Z. Strings without a time zone still fail with
dataCorrupted, and older Foundation versions also reject fractional
seconds such as .732Z, so use a custom strategy that tries
ISO8601FormatStyle with and without fractional seconds if your API
sends them.
How do I mock URLSession in Swift tests?
Subclass URLProtocol, return true from canInit(with:), and in
startLoading() send a canned HTTPURLResponse and body to the
protocol's client. Then create a URLSession from a
URLSessionConfiguration whose protocolClasses contains your
subclass, and pass that session to the code under test. Requests never
leave the process, and your real decoding and error handling still
run.
Is there a JsonFabrica Swift package or XCTest plugin?
No. JsonFabrica is a plain JSON-over-HTTP API, with no Swift package, Xcode plugin, XCTest or Swift Testing extension, or SDK. You write a small regen script, for example with curl and jq, that sends a template and a seed to the API and writes the generated JSON into your test target. Your tests read that committed file, and test runs never call the API.
One seeded fixture gives your Swift tests a single committed table of
API payloads, with planted edge cases and the outcome each should
produce, shared by Swift Testing, XCTest and a URLProtocol stub.
Rendering a raw template with a seed and params is one request to the
JsonFabrica API; the
templates API reference documents the
request body and the { data, meta } response.
Generate realistic test data with JsonFabrica
Describe the shape of your data once, then generate as many fresh, realistic JSON documents as you need via a simple API call.