Skip to content

Wrappers for Swift assertions that take Error instances instead of strings, and the means to test them in XCTest.

License

Notifications You must be signed in to change notification settings

SlaunchaMan/ErrorAssertions

Repository files navigation

ErrorAssertions

tests Documentation Version Swift Package Manager

Wrappers for Swift assertions that take Error instances instead of Strings, and a suite of test functions to test these assertions.

Getting Started

To use ErrorAssertions, simply import it at the top of your Swift source file:

import ErrorAssertions

Just by doing this, since the Swift compiler will prefer imported modules to the main Swift module, you’ll get the ErrorAssertion versions of functions like fatalError(_:file:line:).

Using Error Types

To use an Error instead of a String when calling an assertion method, use the error version:

import ErrorAssertions

doSomething(completionHandler: { error in
    if let error = error {
        fatalError(error)
    }
})

You can use Error types with fatalError(), assert(), assertionFailure(), precondition(), and preconditionFailure().

Testing Assertions

In your tests, import the ErrorAssertionExpectations module to test assertions made in your app (as long as you’ve imported ErrorAssertions). In your test cases, use the expectation methods:

func testThatAnErrorHappens() {
    expectFatalError {
        doAThingThatProducesAFatalError()
    }
}

There are also versions that take an Error or String and validate that the produced error is the one you’re expecting:

func testThatASpecificErrorHappens() {
    expectFatalError(expectedError: URLError.badURL) {
        loadURL("thisisnotaurl")
    }
}

Installation

Swift Package Manager

Swift Package Manager is the preferred way to install ErrorAssertions. Add the repository as a dependency:

dependencies: [
    .package(url: "https://github.com/SlaunchaMan/ErrorAssertions.git",
             from: "0.2.0")
]

In your targets, add ErrorAssertions as a dependency of your main target and, if you’re using the test support, add ErrorAssertionExpectations to the test target:

targets: [
    .target(name: "App", dependencies: ["ErrorAssertions")]
    .testTarget(name: "AppTests", dependencies: ["ErrorAssertionExpectations"])
]

CocoaPods

To use ErrorAssertions with CocoaPods, use the main pod as a dependency in your app and the ErrorAssertionExpectations pod in your tests:

target 'App' do
    pod 'ErrorAssertions'
end

target 'AppTests' do
    pod 'ErrorAssertionExpectatoins'
end

About

Wrappers for Swift assertions that take Error instances instead of strings, and the means to test them in XCTest.

Resources

License

Stars

Watchers

Forks

Packages

No packages published