Jenis test dan test double
Ringkasan satu halaman. Dari Lesson 0010.
Testing pyramid
| Jenis | Menguji | Jumlah | Node |
|---|---|---|---|
| Unit Test | Satu komponen terisolasi (ProductService), I/O diganti test double. Fast, Isolated, Repeatable, Self-Checking, Timely [2] | Paling banyak | Jest + jest.fn() |
| Integration Test | "two or more app components work together": pipeline HTTP → Controller → Service → DB [1] | Sedikit, skenario infrastruktur penting | Supertest |
| E2E | Browser Angular sampai database | Paling sedikit (lambat, flaky) [4] | Playwright / Cypress |
Aturan: "If a behavior can be tested using either a unit test or an integration test, choose the unit test." [1]
Test double [3]
| Istilah | Peran | Moq | Jest |
|---|---|---|---|
| Stub | Jawaban siap; tidak di-assert | Setup(...).ReturnsAsync(x) | mockReturnValue |
| Mock | Panggilannya diverifikasi (behavior verification) [5] | Verify(..., Times.Never()) | toHaveBeenCalled |
| Fake | Implementasi kerja dengan jalan pintas | SQLite in-memory | Repository berbasis array |
| Dummy | Hanya mengisi parameter | Mock.Of<ILogger<T>>() | {} |
new Mock<T>() tanpa Verify berperan sebagai stub. Dokumen .NET memakai "fake" sebagai istilah umum (stub atau mock). [2]
WebApplicationFactory<Program> [1]
- Paket
Microsoft.AspNetCore.Mvc.Testing; menjalankan app diTestServerin-memory, tanpa deploy. public partial class Program { }diProgram.cssupaya test project bisa memakaiProgram(atauInternalsVisibleTo).CreateClient()→HttpClientke TestServer.IClassFixture<ApiFactory>berbagi factory per class.- Override
ConfigureWebHost→builder.ConfigureServices(jalan setelahProgram.cs) untuk mengganti DbContext. - Per test:
WithWebHostBuilder(b => b.ConfigureTestServices(...)).
Apa yang di-mock
| Ya | Tidak |
|---|---|
Batas I/O: IProductRepository, HTTP client keluar, jam sistem | Entity/DTO, SUT, method private, DbSet untuk query (LINQ = extension method statis) [9] |
Database test (saran EF Core [9]): DB produksi asli (Testcontainers) → repository pattern → SQLite in-memory (beda dialek, case-sensitive) → hindari provider EF Core in-memory.
Jawaban 60 detik
Jenis test: unit = satu komponen terisolasi, I/O di-mock, milidetik; integration = beberapa komponen bersama sampai DB; E2E = dari UI. Piramida: makin tinggi makin sedikit.
API diuji dengan WebApplicationFactory (TestServer in-memory, CreateClient), DbContext diganti SQLite/Testcontainers.
Test double: stub = jawaban siap, tidak di-assert; mock = panggilannya di-Verify; fake = implementasi ringan (SQLite in-memory).
Mock batas I/O; jangan mock Entity/DTO, SUT, method private, atau DbSet untuk query.
Sumber: [1] Microsoft Learn: Integration tests in ASP.NET Core · [2] Microsoft Learn: Unit testing best practices · [3] Martin Fowler: TestDouble · [4] The Practical Test Pyramid · [5] Martin Fowler: Mocks Aren't Stubs · [9] EF Core: Choosing a testing strategy