Swift Testing Standards
Priority: P0
Write XCTest Cases
- Standard Naming: Test functions must be prefixed by 'test' (e.g.,
func testUserLoginSuccessful()). - Setup/Teardown: Use
setUpWithError()andtearDownWithError()for environment management. - Assertions: Use specific assertions:
XCTAssertEqual,XCTAssertNil,XCTAssertTrue, etc.
See implementation examples for XCTest setup/teardown, async tests, and UI test patterns.
Test Async Code
- Async/Await: Mark test methods as
async throwsand usetry awaitdirectly inside them. - Expectations: Use
XCTestExpectationfor callback-based async logic. Callexpectationthenfulfill()when done; thenwait(for: [exp], timeout: 2.0)to block. - Timeout: Always set reasonable timeouts for expectations to avoid hanging CI.
Organize Test Suites
- Unit Tests: Use protocols for dependencies and inject them via constructor (e.g.,
init(service: ServiceProtocol)). Focus on logic isolation using mocks/stubs. - UI Tests: Test user flows using
XCUIApplicationand accessibility identifiers. - Coverage: Aim for high coverage on critical business logic and state transitions.
Anti-Patterns
- No Thread.sleep: Use expectations or await.
- No force unwrap in tests: Use XCTUnwrap() for better failure messages.
- No assertion-free tests: A test that only runs code is not a test.