| name | description |
|---|---|
go-tests |
Generates Go unit tests using the Expectation pattern with cmp.Diff. Use when writing, adding, or fixing Go tests, or when working with _test.go files. |
Table-driven tests using the Expectation pattern with cmp.Diff.
func TestFunctionName(t *testing.T) {
t.Parallel()
type Expectation struct {
Result ResultType
Err string
}
tests := []struct {
Name string
Input InputType
Expected Expectation
}{
{
Name: "descriptive_snake_case_name",
Input: inputValue,
Expected: Expectation{
Result: expectedValue,
},
},
}
for _, tc := range tests {
t.Run(tc.Name, func(t *testing.T) {
t.Parallel()
var got Expectation
result, err := FunctionUnderTest(tc.Input)
if err != nil {
got.Err = err.Error()
} else {
got.Result = result
}
if diff := cmp.Diff(tc.Expected, got); diff != "" {
t.Errorf("FunctionUnderTest() mismatch (-want +got):\n%s", diff)
}
})
}
}- Always use
t.Parallel()at test function and subtest level - Never use
t.Parallel()witht.Setenv()- they panic together - Single
cmp.Diffassertion comparing entire Expectation struct - Capture errors as strings in
Expectation.Err, not witht.Fatal - Use
t.Context()instead ofcontext.Background() - Use
t.Cleanup()for resource cleanup, not defer - Use
t.Helper()in helper functions - Never use testify - use
cmp.Diffonly
// Ignore non-deterministic fields
cmpopts.IgnoreFields(Response{}, "CreatedAt", "UpdatedAt")
// Handle unexported fields (generated code)
cmpopts.IgnoreUnexported(db.Environment{})
// Protobuf messages
protocmp.Transform()
// Combine options
cmp.Diff(tc.Expected, got,
protocmp.Transform(),
cmpopts.IgnoreFields(db.Prebuild{}, "CreateTime", "Edges"),
cmpopts.EquateEmpty(),
)For HTTP handler tests, database tests with ExistingObjects, and Setup functions, see examples.md.
t.Fatalfor action errors → useExpectation.Errlen(results) != expected→ compare full resultscontext.Background()→ uset.Context()testify/assert→ usecmp.Diff- Missing
t.Parallel()on independent tests