Skip to content

Commit 61dcf0c

Browse files
authored
Add requireFail. Like fail(), but it also always throws an error (#1163)
1 parent f459a20 commit 61dcf0c

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

Sources/Nimble/DSL+Require.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,3 +289,17 @@ public func unwrapa<T>(fileID: String = #fileID, file: FileString = #filePath, l
289289
public func unwrapa<T>(fileID: String = #fileID, file: FileString = #filePath, line: UInt = #line, column: UInt = #column, customError: Error? = nil, description: String? = nil, _ expression: @autoclosure () -> (() async throws -> T?)) async throws -> T {
290290
try await requirea(fileID: fileID, file: file, line: line, column: column, customError: customError, expression()).toNot(beNil(), description: description)
291291
}
292+
293+
/// Always fails the test and throw an error to prevent further test execution.
294+
///
295+
/// - Parameter message: A custom message to use in place of the default one.
296+
/// - Parameter customError: A custom error to throw in place of a ``RequireError``.
297+
public func requireFail(_ message: String? = nil, customError: Error? = nil, fileID: String = #fileID, filePath: FileString = #filePath, line: UInt = #line, column: UInt = #column) throws {
298+
let location = SourceLocation(fileID: fileID, filePath: filePath, line: line, column: column)
299+
let handler = NimbleEnvironment.activeInstance.assertionHandler
300+
301+
let msg = message ?? "requireFail() always fails"
302+
handler.assert(false, message: FailureMessage(stringValue: msg), location: location)
303+
304+
throw customError ?? RequireError(message: msg, location: location)
305+
}

Tests/NimbleTests/DSLTest.swift

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,4 +219,32 @@ final class DSLTest: XCTestCase {
219219
try await unwrapa(description: "Other Message", await asyncOptional(nil))
220220
}
221221
}
222+
223+
func testRequireFail() throws {
224+
struct MyCustomError: Error {}
225+
226+
failsWithErrorMessage("requireFail() always fails") {
227+
do {
228+
try requireFail()
229+
} catch {
230+
expect(error as? RequireError).toNot(beNil())
231+
}
232+
}
233+
234+
failsWithErrorMessage("Custom error message") {
235+
do {
236+
try requireFail("Custom error message")
237+
} catch {
238+
expect(error as? RequireError).toNot(beNil())
239+
}
240+
}
241+
242+
failsWithErrorMessage("Custom message with custom error") {
243+
do {
244+
try requireFail("Custom message with custom error", customError: MyCustomError())
245+
} catch {
246+
expect(error as? MyCustomError).toNot(beNil())
247+
}
248+
}
249+
}
222250
}

0 commit comments

Comments
 (0)