Skip to content

Commit 5fd1afa

Browse files
heckjstmontgomery
andauthored
Add example for how to test any error is thrown in the error testing documentation article (#853)
I was stumped earlier when trying to find the details for how to test that any error is thrown. This detail _is_ in the migrating from XCTest content, but I landed on this page, and it seemed an odd miss, especially given the history of ignoring the kind of error in many cases. (I found my solution in [a post by Jonathan the forums](https://forums.swift.org/t/swift-testing-whats-the-recommend-approach-to-test-throwing-function/70806/2).) While it is duplicated content, this would have helped me - so I'm proposing it for a documentation update. Happy to edit as y'all see fit. --------- Co-authored-by: Stuart Montgomery <[email protected]>
1 parent 228f0e6 commit 5fd1afa

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

Sources/Testing/Testing.docc/testing-for-errors-in-swift-code.md

+16
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,22 @@ test that the code throws an error of a given type, or matches an arbitrary
4444
Boolean test. Similar overloads of ``require(_:_:sourceLocation:)-5l63q`` stop
4545
running your test if the code doesn't throw the expected error.
4646

47+
### Validate that your code throws any error
48+
49+
To check that the code under test throws an error of any type, pass
50+
`(any Error).self` as the first argument to either
51+
``expect(throws:_:sourceLocation:performing:)-1xr34`` or
52+
``require(_:_:sourceLocation:)-5l63q``:
53+
54+
```swift
55+
@Test func cannotAddToppingToPizzaBeforeStartOfList() {
56+
var order = PizzaToppings(bases: [.calzone, .deepCrust])
57+
#expect(throws: (any Error).self) {
58+
try order.add(topping: .mozarella, toPizzasIn: -1..<0)
59+
}
60+
}
61+
```
62+
4763
### Validate that your code doesn't throw an error
4864

4965
A test function that throws an error fails, which is usually sufficient for

0 commit comments

Comments
 (0)