Testing
Ringkasan
Section titled “Ringkasan”Testing memastikan aplikasi Anda berfungsi dengan benar dan mencegah regresi.
Unit Testing
Section titled “Unit Testing”Menguji Services
Section titled “Menguji Services”func TestUserService_Create(t *testing.T) { service := &UserService{ users: make(map[string]*User), }
if err != nil { t.Fatalf("unexpected error: %v", err) }
}}Testing dengan Mock
Section titled “Testing dengan Mock”type MockDB struct { users map[string]*User}
func (m *MockDB) Create(user *User) error { m.users[user.ID] = user return nil}
func TestUserService_WithMock(t *testing.T) { mockDB := &MockDB{users: make(map[string]*User)} service := &UserService{db: mockDB}
if err != nil { t.Fatal(err) }
if len(mockDB.users) != 1 { t.Error("expected 1 user in mock") }}Integration Testing
Section titled “Integration Testing”Testing dengan Dependensi Nyata
Section titled “Testing dengan Dependensi Nyata”func TestIntegration(t *testing.T) { // Setup test database db, err := sql.Open("sqlite3", ":memory:") if err != nil { t.Fatal(err) } defer db.Close()
// Create schema _, err = db.Exec(`CREATE TABLE users (...)`) if err != nil { t.Fatal(err) }
// Test service service := &UserService{db: db} if err != nil { t.Fatal(err) }
// Verify in database var count int db.QueryRow("SELECT COUNT(*) FROM users").Scan(&count) if count != 1 { t.Errorf("expected 1 user, got %d", count) }}Frontend Testing
Section titled “Frontend Testing”Unit Test JavaScript
Section titled “Unit Test JavaScript”// Using Vitestimport { describe, it, expect } from 'vitest'import { formatDate } from './utils'
describe('formatDate', () => { it('formats date correctly', () => { const date = new Date('2024-01-01') expect(formatDate(date)).toBe('2024-01-01') })})Menguji Bindings
Section titled “Menguji Bindings”import { vi } from 'vitest'import { GetUser } from './bindings/changeme/userservice'
// Mock the bindingvi.mock('./bindings/changeme/userservice', () => ({ GetUser: vi.fn()}))
describe('User Component', () => { it('loads user data', async () => {
// Test your component const user = await GetUser(1) expect(user.name).toBe('John') })})Praktik Terbaik
Section titled “Praktik Terbaik”✅ Lakukan
Section titled “✅ Lakukan”- Tulis tes sebelum memperbaiki bug
- Uji edge case
- Gunakan table-driven tests
- Mock dependensi eksternal
- Uji error handling
- Jaga agar tes tetap cepat
❌ Jangan
Section titled “❌ Jangan”- Jangan lewati kasus error
- Jangan uji detail implementasi
- Jangan tulis tes yang tidak stabil
- Jangan abaikan kegagalan tes
- Jangan lewati integration test
Menjalankan Tes
Section titled “Menjalankan Tes”# Run Go testsgo test ./...
# Run with coveragego test -cover ./...
# Run specific testgo test -run TestUserService
# Run frontend testscd frontend && npm test
# Run with watch modecd frontend && npm test -- --watchLangkah Selanjutnya
Section titled “Langkah Selanjutnya”- End-to-End Testing - Uji alur pengguna secara lengkap
- Best Practices - Pelajari praktik terbaik