Skip to content

Commit cc20ae0

Browse files
committed
add throwing tests rule
1 parent fdd3d2f commit cc20ae0

File tree

1 file changed

+44
-7
lines changed

1 file changed

+44
-7
lines changed

README.md

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4343,21 +4343,21 @@ _You can enable the following settings in Xcode by running [this script](resourc
43434343
## Testing
43444344

43454345
* <a id='prefer-unwrapping-apis'></a>(<a href='#prefer-unwrapping-apis'>link</a>) **Prefer Test APIs for unwrapping optionals over `if let`.** XCTest and Swift Testing have APIs for unwrapping an optional and failing the test, which are much simpler than unwrapping the optionals yourself.
4346+
43464347
<details>
43474348

43484349
```swift
43494350
import XCTest
43504351

43514352
final class SomeTestCase: XCTestCase {
4352-
43534353
func test_something() throws {
4354-
// RIGHT:
4355-
let value = try XCTUnwrap(optionalValue)
4356-
43574354
// WRONG:
43584355
guard let value = optionalValue else {
43594356
XCTFail()
43604357
}
4358+
4359+
// RIGHT:
4360+
let value = try XCTUnwrap(optionalValue)
43614361
}
43624362
}
43634363
```
@@ -4368,17 +4368,54 @@ _You can enable the following settings in Xcode by running [this script](resourc
43684368
struct SomeTests {
43694369
@Test
43704370
func something() throws {
4371-
// RIGHT:
4372-
let value = try #require(optionalValue)
4373-
43744371
// WRONG:
43754372
guard let value = optionalValue {
43764373
return
43774374
}
4375+
4376+
// RIGHT:
4377+
let value = try #require(optionalValue)
4378+
}
4379+
}
4380+
```
4381+
4382+
* <a id='prefer-throwing-tests'></a>(<a href='#prefer-throwing-tests'>link</a>) **Prefer throwing tests to `try!`** `try!` will crash your test suite like a force-unwrapped optional. XCTest and Swift Testing support throwing test methods, so use that instead. [![SwiftFormat: wrap](https://img.shields.io/badge/SwiftFormat-throwingTests-7B0051.svg)](https://github.com/nicklockwood/SwiftFormat/blob/main/Rules.md#throwingTests)
4383+
4384+
<details>
4385+
4386+
```swift
4387+
import XCTest
4388+
4389+
final class SomeTestCase: XCTestCase {
4390+
// WRONG:
4391+
func test_something() {
4392+
try! Something().doSomething()
4393+
}
4394+
4395+
// RIGHT:
4396+
func test_something() throws {
4397+
try Something().doSomething()
43784398
}
43794399
}
43804400
```
43814401

4402+
```swift
4403+
import Testing
4404+
4405+
struct SomeTests {
4406+
// WRONG:
4407+
@Test
4408+
func something() {
4409+
try! Something().doSomething()
4410+
}
4411+
4412+
// RIGHT:
4413+
@Test
4414+
func something() throws {
4415+
try Something().doSomething()
4416+
}
4417+
}
4418+
```
43824419
</details>
43834420

43844421
**[ back to top](#table-of-contents)**

0 commit comments

Comments
 (0)