Package testing golang memiliki beberapa method bawaan untuk keperluan testing seperti t.Fail, t.FailNow, t.Error & t.Fatal, t.Skip. Penjelasan masing-masing method dirinci sebagai berikut:
t.Fail() digunakan untuk menggagalkan unit test, namun tetap melanjutkan eksekusi unit test. Unit test tersebut dianggap gagal.
func (c *common) Fail() {if c.parent !=nil { c.parent.Fail() } c.mu.Lock()defer c.mu.Unlock()// c.done needs to be locked to synchronize checks to c.done in parent tests.if c.done {panic("Fail in goroutine after "+ c.name +" has completed") } c.failed =true}
t.FailNow() digunakan untuk menggagalkan unit test saat ini juga, tanpa melanjutkan eksekusi unit test selanjutnya.
t.Error() digunakan untuk menampilkan error dengan log dan memanggil function Fail(), sehingga eksekusi unit test akan tetap berjalan sampai selesai meskipun unit test saat ini telah gagal.
Berikut contoh code unit testing yang menerapkan method error.
main_test.go
packagemainimport ("fmt""testing"// "github.com/stretchr/testify/assert")funcTestSayHi(t *testing.T) { t.Run("Test-1", func(t *testing.T) { result :=SayHi("Amar")if result !="Andi" { t.Error("Not Andi") } fmt.Println("Next") result =SayHi("Andi")if result !="Andi" { t.Error("Andi") } })}
PS D:\bootcamp-go\go-unit-test> go test -v -run TestSayHi
=== RUN TestSayHi
=== RUN TestSayHi/Test-1
main_test.go:13: Not Andi
Next
main_test.go:18: Andi
--- FAIL: TestSayHi (0.00s)
--- FAIL: TestSayHi/Test-1 (0.00s)
FAIL
exit status 1
FAIL unit-testing 0.374s
Implementasi method Fatal
Berikut contoh code unit testing yang menerapkan method fatal.
main_test.go
packagemainimport ("fmt""testing")funcTestSayHi(t *testing.T) { t.Run("Test-1", func(t *testing.T) { result :=SayHi("Amar")if result !="Andi" { t.Fatal("Not Andi") } fmt.Println("Next") result =SayHi("Andi")if result !="Andi" { t.Fatal("Andi") } })}
PS D:\bootcamp-go\go-unit-test> go test -v -run TestSayHi
=== RUN TestSayHi
=== RUN TestSayHi/Test-1
main_test.go:13: Not Andi
--- FAIL: TestSayHi (0.00s)
--- FAIL: TestSayHi/Test-1 (0.00s)
FAIL
exit status 1
FAIL unit-testing 0.316s
Implementasi method Skip
Berikut contoh code unit testing yang menerapkan method skip.
main_test.go
packagemainimport ("fmt""testing"// "github.com/stretchr/testify/assert")funcTestSayHi(t *testing.T) { t.Run("Test-1", func(t *testing.T) { result :=SayHi("Amar")if result !="Andi" { t.Skip("Not Available") } fmt.Println("Next") result =SayHi("Andi")if result !="Andi" { t.Error("Andi") } })}
PS D:\bootcamp-go\go-unit-test> go test -v -run TestSayHi
=== RUN TestSayHi
=== RUN TestSayHi/Test-1
main_test.go:13: Not Available
--- PASS: TestSayHi (0.00s)
--- SKIP: TestSayHi/Test-1 (0.00s)
PASS
ok unit-testing 0.270s