func TestWithResource(t *testing.T) { r, err := getResource() if err != nil { t.Fatal(err) } defer r.close() if r.state != expectedState { t.Fatal("unexpected resource state") } // test code that depends on the resource being in the expected state }
func TestNoPanic(t *testing.T) { defer func() { if r := recover(); r != nil { t.Fatal("expected no panic, but one occurred") } }() // test code that should not panic foo(nil) } func foo(s *string) { if s == nil { panic("nil pointer") } }In this example, we use a defer statement to recover from any panic that might occur in the test code. If a panic occurs, we use t.Fatal() to immediately mark the test as failed and stop its execution. The testing package provides the TB interface as part of its core API.