|
| 1 | +--- |
| 2 | +description: Swift testing best practices and requirements |
| 3 | +globs: ["Tests/**/*.swift"] |
| 4 | +alwaysApply: true |
| 5 | +--- |
| 6 | + |
| 7 | +# SWIFT TESTING RULES |
| 8 | + |
| 9 | +## Test Structure Requirements |
| 10 | + |
| 11 | +### DO: |
| 12 | +- Create separate test methods for each test case |
| 13 | +- Use `guard` statements with `XCTFail` for unwrapping optionals |
| 14 | +```swift |
| 15 | +func testSomething() { |
| 16 | + guard let result = someOptionalValue else { |
| 17 | + XCTFail("Expected non-nil value") |
| 18 | + return |
| 19 | + } |
| 20 | + XCTAssertEqual(result, expectedValue) |
| 21 | +} |
| 22 | +``` |
| 23 | +- Write focused tests that test one thing at a time |
| 24 | +- Use descriptive test method names in the format `test_<methodName>_<withCircumstances>_<shouldExpectation>` |
| 25 | +``` |
| 26 | + func test_canTransition_fromAppleSheetPresentedState_shouldAllowPaymentAuthorizationAndInterruptAndCompleted() |
| 27 | + func test_ensureCurrencyNotChanged_withNoInitialCurrency_shouldNotThrow() |
| 28 | +``` |
| 29 | + |
| 30 | +- If a function may throw multiple types of errors, write multiple tests to capture them in isolation |
| 31 | +``` |
| 32 | +func throwingFunction() { |
| 33 | + if someCondition { |
| 34 | + throw Error.foo |
| 35 | + } else |
| 36 | + throw Error.bar |
| 37 | + } |
| 38 | + |
| 39 | + func test_throwingFunction_whenSomeConditionTrue_shouldThrowFoo() { |
| 40 | + do { |
| 41 | + _ = try await storefront.createCart() |
| 42 | + XCTFail("Expected error to be thrown") |
| 43 | + } catch { |
| 44 | + guard case let error = Error.foo else { |
| 45 | + XCTFail("Expected .foo") |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + func test_throwingFunction_whenSomeConditionTrue_shouldThrowBar(){ |
| 50 | + do { |
| 51 | + _ = try await storefront.createCart() |
| 52 | + XCTFail("Expected error to be thrown") |
| 53 | + } catch { |
| 54 | + guard case let error = Error.foo else { |
| 55 | + XCTFail("Expected .foo") |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +``` |
| 60 | + |
| 61 | +## Code Examples |
| 62 | + |
| 63 | +### ✅ CORRECT: Unwrapping optionals |
| 64 | +```swift |
| 65 | +func testSomething() { |
| 66 | + guard let result = someOptionalValue else { |
| 67 | + XCTFail("Expected non-nil value") |
| 68 | + return |
| 69 | + } |
| 70 | + XCTAssertEqual(result, expectedValue) |
| 71 | +} |
| 72 | +``` |
| 73 | + |
| 74 | +### DON'T: |
| 75 | +- Use typed catches when testing throwing expressions |
| 76 | +- Delete and recreate test files when debugging |
| 77 | +- Add boilerplate comments like "// Given", "// When", "// Then" |
| 78 | + |
| 79 | +## Comments |
| 80 | + |
| 81 | +- Use comments ONLY to explain non-obvious side effects or complex reasoning |
| 82 | +- Keep comments minimal and purposeful |
| 83 | +- Focus on WHY something is done, not WHAT is being done |
0 commit comments