Replace manual if-error checks with `testify`'s `assert` and `require` packages to make tests more readable, maintainable, and with better error messages.
Replace manual if-error checks with testify
’s assert
and require
packages to make tests more readable, maintainable, and with better error messages.
When to use each:
assert
for non-critical checks that should report failures but continue testingrequire
for checks that should halt the test if they failKey improvements:
// After assert.True(t, ok, “Value should be found in cache”) assert.Equal(t, data, v, “Cache should return correct value”)
2. **Split compound conditions into separate assertions**
```go
// Before
if !triggered1 || !triggered2 {
t.Errorf("not all matching listeners triggered")
}
// After
assert.True(t, triggered1, "First listener should be triggered")
assert.True(t, triggered2, "Second listener should be triggered")
// After assert.EqualValues(t, 1, h.Records()[0].(mod10))
4. **Use specialized assertions for common operations**
```go
// Before
if len(values) != 1 {
t.Errorf("Expected exactly one value, got %d", len(values))
}
// After
require.Len(t, values, 1, "Should have exactly one value")
// After require.Error(t, err, “Operation should return an error”) // Or to check specific error text require.ErrorContains(t, err, “expected error message”) ```
Using these assertion functions consistently improves readability, provides better error messages, and makes tests more maintainable.
Enter the URL of a public GitHub repository