Section 5/121 menit

5. Parameterized Tests

5. Parameterized Tests

Argumen Sederhana

swift
// Satu parameter — test dijalankan untuk setiap nilai
@Test("Validate email format", arguments: [
    "user@example.com",
    "name.surname@domain.org",
    "user+tag@mail.co.id"
])
func validEmailFormats(email: String) {
    #expect(EmailValidator.isValid(email))
}

@Test("Reject invalid emails", arguments: [
    "notanemail",
    "@domain.com",
    "user@",
    "",
    "user @domain.com"  // spasi tidak valid
])
func invalidEmailFormats(email: String) {
    #expect(!EmailValidator.isValid(email))
}

Multiple Parameters dengan zip

swift
// Dua array yang di-zip — pasangan (input, expected)
@Test(
    "Temperature conversion",
    arguments: zip(
        [0.0, 100.0, -40.0, 37.0],    // Celsius
        [32.0, 212.0, -40.0, 98.6]    // Fahrenheit
    )
)
func celsiusToFahrenheit(celsius: Double, expectedFahrenheit: Double) {
    let result = Temperature.celsiusToFahrenheit(celsius)
    #expect(abs(result - expectedFahrenheit) < 0.01)
}

Cartesian Product (semua kombinasi)

swift
// Tanpa zip = cartesian product — semua kombinasi
@Test(
    "HTTP methods dan endpoints",
    arguments: ["GET", "POST", "PUT", "DELETE"],
             ["/users", "/orders", "/products"]
)
func apiEndpointAccessControl(method: String, path: String) async throws {
    let response = try await client.request(method: method, path: path)
    // Test bahwa auth bekerja untuk semua kombinasi
    #expect(response.statusCode != 401)
}
// Total: 4 × 3 = 12 test cases — semua dijalankan paralel!

Argumen dengan Custom Type

swift
struct TestCase {
    let input: String
    let expected: Int
    let description: String
}

@Test("Parse integer", arguments: [
    TestCase(input: "42", expected: 42, description: "positif"),
    TestCase(input: "-10", expected: -10, description: "negatif"),
    TestCase(input: "0", expected: 0, description: "nol"),
])
func parseInteger(_ testCase: TestCase) throws {
    let result = try parseInt(testCase.input)
    #expect(result == testCase.expected, "\(testCase.description) gagal")
}