Section 3/161 menit

3. Teori: Arsitektura Swift Testing

3. Teori: Arsitektura Swift Testing

Test Discovery: Macro-Based, Bukan Runtime Reflection

XCTest menggunakan Objective-C runtime untuk discover test methods (semua method yang mulai test). Swift Testing menggunakan macros dan static metadata — tidak ada runtime scanning.

swift
Build time:
  @Test macro → menghasilkan Test instance dengan metadata
  @Suite macro → menghasilkan Suite instance yang berisi Test instances
  Semua Test/Suite di-register ke global test list via compiler

Runtime:
  Test runner membaca global test list (sudah diketahui di compile time)
  Filter berdasarkan --filter, tags, enabled conditions
  Jalankan test secara paralel (default) atau serial (.serialized)

Model Eksekusi Paralel

swift
Swift Testing Test Runner
    │
    ├── Task untuk test A ──→ berjalan di cooperative thread pool
    ├── Task untuk test B ──→ berjalan di cooperative thread pool
    ├── Task untuk test C ──→ berjalan di cooperative thread pool
    └── Task untuk test D ──→ berjalan di cooperative thread pool

Default: PARALEL (seperti async code)
@Suite(.serialized): SERIAL (satu per satu dalam suite)

Setiap @Test function berjalan dalam Task terpisah. Ini berarti:

  • Test yang tidak share state berjalan lebih cepat (paralel)
  • Test yang share mutable state butuh .serialized atau isolation eksplisit
  • await dalam test berfungsi seperti biasa — tidak memblokir test lain

#expect vs #require — Perbedaan Semantik

swift
#expect(condition):
  - Jika gagal: catat failure, LANJUTKAN test
  - Bisa ada beberapa #expect yang gagal dalam satu test
  - Gunakan untuk: assertion yang tidak kritis untuk kelanjutan test

#require(condition):
  - Jika gagal: catat failure, HENTIKAN test (throw)
  - Setelah #require gagal, kode berikutnya tidak dijalankan
  - Gunakan untuk: precondition yang harus terpenuhi untuk test bermakna