How do you write tests for Swift methods that have preconditions? Here is an example:
func doublePositive(n:Int) -> Int {
precondition(n >= 0)
return 2*n
}
Using XCTAssertThrowsError
does not work:
func testDoublePositive() {
XCTAssertEqual(10, testObject.doublePositive(5)) // Works
XCTAssertThrowsError(testObject.doublePositive(-1)) // Breaks
}
This generates an error when running the test:
Thread 1:EXEC_BAD_INSTRUCTION (Code=EXCI386_INVOP, Subcode=0x0)
Is there a way to test preconditions of Swift?
precondition() works identically to assert() : give it a condition to check along with an optional message to print if the check fails. At runtime – even in release mode – Swift will run the check for you and crash if the check fails. For example: precondition(users.
Testing Swift will give you a thorough grounding in the key testing techniques when working in app development. You'll learn how to benchmark performance, detect regressions, mock components, refactor for testability, and more.
You test Swift methods that have preconditions by only testing behavior with inputs that meet those preconditions. The behavior when the precondition is not met is clear without further testing, since preconditions are baked into the standard library.
If you doubt you've correctly specified a precondition, you can pull out the precondition expression into a Boolean function, then test that for correctly discerning valid from invalid inputs.
However, you can create for yourself what you wish for here:
An option to generate exceptions on precondition/assertion failures would do the trick: one would turn it on in debug builds, and turn it off in release builds.
Instead of calling Apple's precondition
, you can write your own function, say, require
. This could be conditionally compiled to act as you wish. You would then use this everywhere you'd otherwise be using precondition
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With