This package has some generic helpers to facilitate writing table driven tests with mockery/testify mocks. These tests are where one single meta-test is written which is then configured by a passed in struct, which defines the actual test behaviour.
Using this package, you can write a single test function that can be configured to run multiple test cases. This is useful when you have a lot of similar test cases that only differ in the input data or the expected output.
It's also clearer to see what each test is doing, how they differ, and reason about cases that could be missing. Fewer lines of code are needed to write the tests, and the tests are more readable and maintainable as a result.
Once you have installed the package, you can start using it in your tests.
go get github.com/mattavos/tpp
Click to expand
package example_test
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/your/repo/mocks"
"github.com/your/repo/subject"
"github.com/mattavos/tpp"
)
func TestXXX(t *testing.T) {
for _, tt := range []struct {
name string
getFoo tpp.Expect
wantErr bool
}{
{
name: "OK",
getFoo: tpp.Return("foo", nil),
wantErr: false
},
{
name: "ERR: getFoo",
getFoo: tpp.Err(),
wantErr: true,
},
{
name: "BLANK",
wantErr: false
},
} {
t.Run(tt.name, func(t *testing.T) {
mock := mymocks.NewBar(t)
// This configures the given mock call according to the
// Expect. For example, in the first test case it will
// configure the mock to return ("foo", nil). In the
// second, it will configure it to return ("", someErr).
// In the third, it will configure it to return empty
// values ("", nil) and make it an optional call with
// Maybe().
tt.getFoo.Expectorise(mock.EXPECT().GetFoo())
subject := subject.New(mock)
err := subject.XXX()
require.Equal(t, tt.wantErr, err != nil)
})
}
}