Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Swift code with preconditions

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?

like image 246
Sergey Kalinichenko Avatar asked Apr 18 '16 11:04

Sergey Kalinichenko


People also ask

How to use precondition in 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.

What is swift testing?

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.


1 Answers

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.

like image 137
Jeremy W. Sherman Avatar answered Oct 13 '22 11:10

Jeremy W. Sherman