There is no way to test assert or precondition in Swift

Originator:joshavant
Number:rdar://22164396 Date Originated:05-Aug-2015 07:23 PM
Status:Duplicate of 20195010 Resolved:
Product:iOS SDK 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:
Xcode Version 6.1.1 (6A2008a), Xcode Version 6.3 (6D532l), OS X 10.10.2

Attachments:

Comments

Apple Developer Relations26-Aug-2015 03:06 PM

Engineering has determined that your bug report is a duplicate of another issue and will be closed.

The open or closed status of the original bug report your issue was duplicated to appears in the yellow "Duplicate of XXXXXXXX" section of the bug reporter user interface. This section appears near the top of the right column's bug detail view just under the bug number, title, state, product and rank.

If you have any questions or concerns, please update your report directly here: http://bugreport.apple.com/.

By joshavant at Nov. 3, 2015, 6:52 p.m. (reply...)

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!