Skip to content

Commit 7df52d2

Browse files
committed
Add ArbitraryError and support for default stub values
- Add the DefaultStubValueProviding protocol, which lets a type provide a default value for stubs that return it. Conform common standard library and Foundation types, using recognizable placeholder values where possible. - Add Stub.init(), which returns the default stub value until the stub is configured, for return types that conform to DefaultStubValueProviding. - Add ThrowingStub.init() for stubs whose error type is any Error. It throws an unspecified error until the stub is configured. - Add ArbitraryError, an error type for tests that just need an error to throw, and a randomError function on RandomValueGenerating that creates one with a random description beginning with the calling file and function. - Rewrite the guidance on stub properties in Using Stubs to recommend default-initialized stubs, and document ArbitraryError. - Rename the randomError example in Using Random Value Generation so it doesn’t collide with the new function. - Mention the new types in the README and add a 1.7.0 changelog entry.
1 parent 4fb3c49 commit 7df52d2

14 files changed

Lines changed: 559 additions & 10 deletions

‎CHANGELOG.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,25 @@
11
# DevTesting Changelog
22

3+
## 1.7.0: November 13, 2026
4+
5+
This release makes it possible to create stubs that return a placeholder value until they’re
6+
configured, so that a test that calls an unconfigured stub fails instead of crashing.
7+
8+
- The new `DefaultStubValueProviding` protocol lets a type provide a default value for stubs that
9+
return it. DevTesting conforms common standard library and Foundation types, including
10+
`Array`, `Bool`, `Data`, `Date`, `Dictionary`, floating point and integer types, `Optional`,
11+
`Set`, `String`, `URL`, and `UUID`.
12+
- `Stub` has a new `init()` that returns the default stub value until configured, available when
13+
its return type conforms to `DefaultStubValueProviding`.
14+
- `ThrowingStub` has a new `init()` for stubs whose error type is `any Error`. It throws an
15+
unspecified error until configured.
16+
- The new `ArbitraryError` type is an error for tests that just need an error to throw.
17+
`RandomValueGenerating` has a new `randomError(fileID:function:)` function that creates
18+
one with a random description beginning with the calling file and function. If your tests
19+
already extend `RandomValueGenerating` with a function named `randomError`, you may need to
20+
rename or remove it to avoid ambiguous calls.
21+
22+
323
## 1.6.0: June 16, 2026
424

525
This release moves DevTesting’s seedable random number generator and random value generation

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,17 @@ and DevRandom. The primary library for automated testing is DevTesting. It provi
1111
- Case iterables
1212
- Data
1313
- Dates
14+
- Errors
1415
- Floating point types
1516
- Integer types
1617
- Optionals
1718
- Strings
1819
- UUIDs
1920
- URLs, URL components, and URL query items
2021
- `Stub` and `ThrowingStub`, which provide stubbing and spying functionality for your mocks.
22+
Stubs whose return types conform to `DefaultStubValueProviding` can be created without
23+
arguments, so that unconfigured stubs return placeholder values instead of crashing.
24+
- `ArbitraryError`, an error type for tests that just need an error to throw.
2125

2226
DevRandom is a supporting library that includes the core random value generation code. It is used by
2327
DevTesting, but can also be used in your application for random value generation.

‎Sources/DevTesting/Documentation.docc/Documentation.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ detailed information about how those dependencies were used.
3434
- <doc:UsingStubs>
3535
- ``Stub``
3636
- ``ThrowingStub``
37+
- ``DefaultStubValueProviding``
38+
- ``ArbitraryError``
3739

3840
### Collection Generation Extensions
3941

‎Sources/DevTesting/Documentation.docc/RandomValueGenerating.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@
2222
- ``randomDate(in:)-(Range<Date>)``
2323

2424

25+
### Errors
26+
27+
- ``randomError(fileID:function:)``
28+
29+
2530
### Numeric Types
2631

2732
- ``randomFloat64(in:)-(Range<Float64>)``

‎Sources/DevTesting/Documentation.docc/UsingRandomValueGeneration.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,7 @@ types. For example:
361361
}
362362

363363

364-
mutating func randomError() -> MyAppError {
364+
mutating func randomAppError() -> MyAppError {
365365
return MyAppError(code: randomInt(in: 100 ..< 1000))
366366
}
367367

‎Sources/DevTesting/Documentation.docc/UsingStubs.md‎

Lines changed: 56 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -112,22 +112,57 @@ This pattern is especially valuable when writing assertions about how your code
112112
function, as you can easily access specific parameters from the recorded calls.
113113

114114

115-
### Force unwrapping stub properties
115+
### Default-initialized stub properties
116116

117-
Stub properties are declared as implicitly unwrapped optionals to fail fast when stubs are not set
118-
up correctly. By using implicitly unwrapped optionals, failing to properly mock a required
119-
dependency will crash immediately at test time, making it obvious what went wrong.
117+
Where possible, initialize stub properties with a default stub, so that a test that calls a stub
118+
it didn’t configure gets a value instead of crashing:
120119

121120
final class MockFileManager: FileManager {
122-
var documentsDirectoryStub: Stub<Void, URL>!
121+
// Returns URL.defaultStubValue until configured
122+
var documentsDirectoryStub = Stub<Void, URL>()
123123

124-
// If this stub isn’t initialized and the property is accessed, the test will crash
125-
// immediately with a clear error
126-
var documentsDirectory: URL {
127-
documentsDirectoryStub()
124+
// Throws an unspecified error until configured
125+
var loadContentStub = ThrowingStub<String, Data, any Error>()
126+
127+
…
128+
}
129+
130+
A crash in an unconfigured stub can be hard to trace, especially when tests run in parallel, and it
131+
ends the whole test run. A default value lets the test continue, and in most cases fail, without
132+
taking other tests down with it.
133+
134+
`Stub()` is available when the stub’s return type conforms to ``DefaultStubValueProviding``.
135+
DevTesting provides conformances for common standard library and Foundation types, using values
136+
that are recognizable placeholders where possible, such as `1_234_567_890` and `"default stub"`.
137+
Conform your own types by composing their properties’ defaults:
138+
139+
extension Person: DefaultStubValueProviding {
140+
static var defaultStubValue: Person {
141+
return Person(
142+
givenName: .defaultStubValue,
143+
familyName: .defaultStubValue,
144+
age: .defaultStubValue,
145+
)
128146
}
129147
}
130148

149+
A default value only keeps an unconfigured stub from crashing. It isn’t meant to be realistic, so
150+
tests should still configure every stub whose return value they depend on. Similarly, a throwing
151+
stub that throws `any Error` throws by default, so a test of a success path must configure it.
152+
153+
154+
### Force unwrapping stub properties
155+
156+
When a stub’s return type has no default value, or the stub throws a specific error type, declare
157+
the stub property as an implicitly unwrapped optional. Tests must configure these stubs before
158+
they’re called, or the test crashes.
159+
160+
final class MockFileManager: FileManager {
161+
var fileHandleStub: Stub<String, FileHandle>!
162+
163+
…
164+
}
165+
131166

132167
## Configuring Stub Behavior
133168

@@ -154,6 +189,18 @@ For ``ThrowingStub``, you can configure default success or failure behavior:
154189
// Always throw the same error
155190
fileManager.loadContentStub = ThrowingStub(defaultResult: .failure(FileError.notFound))
156191

192+
When a test only needs _an_ error, rather than a specific one, use an ``ArbitraryError``. You can
193+
create one with a description, or with
194+
``RandomValueGenerating/randomError(fileID:function:)``, which gives it a random description
195+
that begins with the calling file and function:
196+
197+
let error = randomError()
198+
fileManager.loadContentStub = ThrowingStub(defaultError: error)
199+
200+
#expect(throws: error) {
201+
try documentLoader.loadDocument(at: path)
202+
}
203+
157204

158205
### Result queues
159206

‎Sources/DevTesting/Random Value Generation/RandomValueGenerating.swift‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,24 @@ extension RandomValueGenerating {
183183
}
184184

185185

186+
// MARK: - Errors
187+
188+
/// Returns an arbitrary error with a random description.
189+
///
190+
/// The description begins with the file ID and function that called this function, which makes it easier to tell
191+
/// where an error came from when a test fails.
192+
///
193+
/// - Parameters:
194+
/// - fileID: The file ID of the caller. Defaults to the caller’s file ID.
195+
/// - function: The name of the calling function. Defaults to the caller’s function name.
196+
public mutating func randomError(
197+
fileID: StaticString = #fileID,
198+
function: StaticString = #function,
199+
) -> ArbitraryError {
200+
return ArbitraryError(description: "\(fileID):\(function)_\(randomAlphanumericString())")
201+
}
202+
203+
186204
// MARK: - Numeric Types
187205

188206
/// Returns a random binary floating point of the specified type within the specified range.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//
2+
// ArbitraryError.swift
3+
// DevTesting
4+
//
5+
// Created by Prachi Gauriar on 11/13/26.
6+
//
7+
8+
import Foundation
9+
10+
/// An error for use in tests, such as the error a stub throws.
11+
///
12+
/// Use an arbitrary error when a test needs an error whose only job is to be thrown and recognized, as in
13+
///
14+
/// let error = randomError()
15+
/// mockFileManager.loadContentStub = ThrowingStub(defaultError: error)
16+
///
17+
/// #expect(throws: error) {
18+
/// try documentLoader.loadDocument(at: path)
19+
/// }
20+
public struct ArbitraryError: Error, CustomDebugStringConvertible, Hashable, Sendable {
21+
/// A description of the error.
22+
public let description: String
23+
24+
25+
/// Creates a new arbitrary error with the specified description.
26+
///
27+
/// - Parameter description: A description of the error.
28+
public init(description: String) {
29+
self.description = description
30+
}
31+
32+
33+
public var debugDescription: String {
34+
return description
35+
}
36+
}

0 commit comments

Comments
 (0)