Hi everyone,
I’ve released the very first version of go-mock-gen: a type-safe, minimal and zero-dependency mock generator with a strong focus on Developer Experience.
Key insights
- Zero Dependencies.
- No Magic: no
any,interface{}, or magic matchers; everything is explicit and type-safe. - Minimalist: a small and clean API surface without the bloat of methods like
Once(),Twice(), orTimes(). - Fail-fast: if something went wrong (e.g., an argument mismatch), the test fails immediately.
- Syntax-Level Enforcement: the generated API is designed to guide you toward correct usage at the syntax level. If you do manage to use it incorrectly, the error messages are explicit about what went wrong and how to fix it.
Quick Look
given you have an interface like this:
type User struct{}
type Repository interface {
CreateUser(ctx context.Context, username string, age int) (User, error)
}
generate command
go run nhatp.com/go/mock-gen/cmd/go-mock-gen -i Repository -o mock_repo_test.go
use EXPECT for convenience
repo := testRepository()
// expect called, ignored args, return zero
repo.EXPECT().CreateUser(t)
// expect called, stub return, ignore args
repo.EXPECT().CreateUser(t).Return(User{}, errors.New("whatever"))
// expect called, match a single argument, ignore others
repo.EXPECT().CreateUser(t).WithUsername("expected-username")
// expect called, match all arguments via callback and stub return
repo.EXPECT().CreateUser(t).Match(func (ctx context.Context, username string, age int) bool {
return true
}).Return(User{}, errors.New("whatever"))
use STUB for fine-grained control
repo = testRepository()
spy := repo.STUB().CreateUser(func(ctx Context, username string, age int) (User, error) {
// do assert yourself
return User{}, nil
})
repo.CreateUser(ctx, username, age)
// do assert yourself
fmt.Println(spy)
There is a Live Demo that you can play with in your browser.
I hope you like it. Thank you!