Golang / GoLang System Architecture and Testing Interview Questions
What testing.T methods do experienced Go engineers use to write cleaner tests?
Beyond t.Error and t.Fatal, Go's testing package offers several methods that eliminate boilerplate and make test intent clearer. Knowing these marks a candidate as familiar with Go testing idioms.
// t.Helper() â marks current function as a test helper // Error messages show the caller's line, not the helper's line func requireNoError(t *testing.T, err error, msg string) { t.Helper() // CRITICAL: without this, failure shows helper's line if err != nil { t.Fatalf("%s: %v", msg, err) } } // t.Cleanup() â deferred cleanup, runs even if test panics func TestDBOperation(t *testing.T) { db := openTestDB(t) t.Cleanup(func() { db.Close() }) // cleaner than defer for table tests user := createTestUser(t, db) t.Cleanup(func() { db.Exec("DELETE FROM users WHERE id = $1", user.ID) }) // test code... } // t.Setenv() â sets env var for the test, auto-restores on cleanup func TestLoadConfig(t *testing.T) { t.Setenv("DATABASE_URL", "postgres://test:test@localhost/testdb") t.Setenv("JWT_SECRET", "test-secret-at-least-32-chars-long") cfg, err := loadConfig() requireNoError(t, err, "loadConfig") if cfg.Database.URL == "" { t.Error("DATABASE_URL not loaded") } } // t.TempDir() â creates a temp directory that's auto-removed func TestWriteFile(t *testing.T) { dir := t.TempDir() // automatically cleaned up after test path := filepath.Join(dir, "output.json") err := writeJSON(path, map[string]string{"ok": "true"}) requireNoError(t, err, "writeJSON") } // t.Parallel() â run subtests concurrently for faster test suites func TestConcurrentOperations(t *testing.T) { for _, tc := range testCases { tc := tc // capture pre-Go 1.22 t.Run(tc.name, func(t *testing.T) { t.Parallel() // this subtest runs concurrently with others // ... test body }) } }
More Related questions...