This library is deprecated. You can use https://github.com/mattgallagher/CwlPreconditionTesting instead.
Finally, you can achieve 100% coverage. Previously, you couldn't because you cannot test assert
, assertionFailure
, precondition
, preconditionFailure
and fatalError
. But now with every easy steps you can test them.
This is an example app to show you how to do it. When you test command + U
the app. You will find many test cases fail. This is intentional, to show that expectAssert
for example fails the test case with a proper error message when the assert function is not called.
When you go to the coverage, you finally can see that we have 100% coverage.
- Drop
ProgrammerAssertions.swift
to the target of your app or framework under test. Just besides your source code. - Drop
XCTestCase+ProgrammerAssertions.swift
to your test target. Just besides your test cases. - Use
assert
,assertionFailure
,precondition
,preconditionFailure
andfatalError
normally as you always do. - Unit test them with the new methods
expectAssert
,expectAssertionFailure
,expectPrecondition
,expectPreconditionFailure
andexpectFatalError
.
For example: If you have a function that does a division like the following:
func divideFatalError(x: Float, by y: Float) -> Float {
guard y != 0 else {
fatalError("Zero division")
}
return x / y
}
You can test the 0 division with the following code.
func testFatalCorrectMessage() {
expectFatalError("Zero division") {
divideFatalError(1, by: 0)
}
}
Or if you don't want to test the message, you simply do.
func testFatalErrorNoMessage() {
expectFatalError() {
divideFatalError(1, by: 0)
}
}
Thanks to nschum and Ken Ko they have the credit for creating these reusable files. I just added very few stuff.
Mohamed Afifi, [email protected]
AssertionsTestingExample is available under the MIT license. See the LICENSE file for more info.