Go Testing dengan Testify
Definisi
testify adalah library populer yang menambah assert (lanjut meski gagal) dan require (berhenti jika gagal) serta suite untuk mengelompokkan test dengan setup/teardown. Membuat test Go lebih ringkas dari if got != want.
Kapan dipakai
Pakai saat ingin assertion ekspresif tanpa boilerplate t.Errorf. suite berguna bila banyak test butuh state bersama (DB test, fixtures).
Cara kerja
assert vs require
import "github.com/stretchr/testify/assert"
func TestAdd(t *testing.T) {
got := Add(2, 3)
assert.Equal(t, 5, got) // lanjut walau fail
require.Equal(t, 5, got) // stop bila fail
}Suite
type UserSuite struct { suite.Suite; db *sql.DB }
func (s *UserSuite) SetupTest() { s.db = setupTestDB() }
func (s *UserSuite) TestCreate() { s.Equal(1, createUser(s.db)) }
func TestRun(t *testing.T) { suite.Run(t, new(UserSuite)) }Struktur alur
Loading diagram...
Catatan implementasi
requiredi awal test untuk guard precondition;assertuntuk banyak cek bertahap.suitepunyaSetupTest/TearDownTestper test;SetupSuiteuntuk sekali.- Bisa padukan dengan
mockpackage testify untuk interface fake. - Pastikan
go.modsudah ada testify; jangan lupat.Parallelhati-hati di suite.
Kesalahan umum
- require di loop tanpa subtest: stop seluruh test, bukan satu kasus.
- State suite bocor antar test: reset di SetupTest.
- Mock terlalu ketat: hanya verifikasi yang penting.
- assert tanpa fail message: tambahkan pesan untuk debug cepat.