There is no way to test assert or precondition in Swift

Originator:B.Gesiak
Number:rdar://20066350 Date Originated:05-Mar-2015 11:33 PM
Status:Open Resolved:
Product:Developer Tools Product Version:
Classification: Reproducible:
 
Summary:
The Swift standard library doesn’t provide any concept of an “exception”. In order to indicate user error, Swift conventionally uses assert or precondition. However, there is no way to test that production code–code I’ll be shipping to users of my app–triggers an assert or precondition. All three of the following functions are untestable:

```
public func decrement(x: UInt) -> UInt {
  return x - 1  // Crashes if x == 0
}

public func decrementWithAssert(x: Int) -> Int {
  assert(x > 0)
  return x - 1
}

public func decrementWithPrecondition(x: Int) -> Int {
  precondition(x > 0)
  return x - 1
}
```

The only way to test whether this Swift code triggers an assert is by waiting for crash reports from my users.

Steps to Reproduce:
1. Write a public Swift function that, given an integer, asserts that the integer must be less than or equal to 10:

```
public func dieIfGreaterThanTen(x: Int) {
    assert(x <= 10)
}
```

2. Attempt to write a unit test for that function.

Expected Results:
I am able to write a unit test, such as:

```
func testDie_whenXIsGreaterThanTen_doesNotTriggerAssert() {
    XCTAssertDoesNotAssert { dieIfGreaterThanTen(9) }
}

func testDie_whenXIsGreaterThanTen_triggersAssert() {
    XCTAssertAsserts { dieIfGreaterThanTen(11) }
}
```

Actual Results:
There is no way to unit test the function.

Version:
Xcode Version 6.1.1 (6A2008a), Xcode Version 6.3 (6D532l), OS X 10.10.2

Notes:


Configuration:


Attachments:

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!