Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

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?

Upvotes: 12

Views: 3172

Answers (1)

Jeremy W. Sherman
Jeremy W. Sherman

Reputation: 36143

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.

Upvotes: 8

Related Questions