Testing Fast Code with Prerequisites

How do you write tests for Swift methods with 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 causes an error when starting the test:

Subject 1: EXEC_BAD_INSTRUCTION (Code = EXCI386_INVOP, Subcode = 0x0)

Is there a way to test Swift prerequisites?

+5
source share
1 answer

You test Swift methods that have prerequisites by only testing behavior with inputs that match these prerequisites. The behavior when the precondition is not met becomes clear without further testing, since the preconditions are baked into the standard library.

If you doubt that you have correctly set the precondition, you can output the precondition expression to a logical function, and then check that for the correct recognition of valid values ​​with invalid inputs.

However, you can create for yourself what you want here:

The option of throwing exceptions for failures with a precondition / statement would do the trick: one would include it in debug builds and disable it in release builds.

Instead of calling Apple precondition you can write your own function, say require . This can be conditionally compiled to act according to your desire. Then you would use it wherever you use precondition .

+3
source

Source: https://habr.com/ru/post/1247358/


All Articles