Section 10/161 menit
10. Exit Tests: Testing Crash dan `fatalError`
10. Exit Tests: Testing Crash dan fatalError
Swift Testing mendukung testing kode yang seharusnya crash/exit melalui #expect(exitsWith:).
Dasar Exit Tests
swift
// Test bahwa fatalError dipanggil pada kondisi invalid
@Test
func testPreconditionFailure() async {
await #expect(exitsWith: .failure) {
// Kode ini harus crash
_ = Array<Int>()[100] // Index out of bounds → crash
}
}
// Test bahwa crash dengan exit code tertentu
@Test
func testFatalErrorOnInvalidState() async {
await #expect(exitsWith: .failure) {
validateConfiguration(nil) // Nil config → fatalError
}
}
// Test bahwa kode TIDAK crash (exit sukses)
@Test
func testValidInputDoesNotCrash() async {
await #expect(exitsWith: .success) {
validateConfiguration(Config.default) // Valid config → tidak crash
}
}
Exit Test untuk Custom Preconditions
swift
// Production code
func initializeDatabase(path: String?) {
guard let path else {
fatalError("Database path tidak boleh nil")
}
// Setup database
}
// Test
@Test
func testDatabaseInitWithNilPath() async {
await #expect(exitsWith: .failure) {
initializeDatabase(path: nil) // Harus crash dengan fatalError
}
}
@Test
func testDatabaseInitWithValidPath() async {
await #expect(exitsWith: .success) {
initializeDatabase(path: "/tmp/test.db") // Tidak crash
}
}
Catatan: Exit tests berjalan di subprocess terpisah — ini penting untuk isolasi. State parent process tidak terpengaruh oleh crash di exit test.