📢 Introducing gs-mock: A Type-Safe and Generic Mocking Library for Go

Hi Gophers :waving_hand:,

I’d like to share a project I’ve been working on: gs-mock — a modern, type-safe mocking library for Go that fully supports generics.

Why another mocking library?

Traditional Go mocking tools often:

  • Rely on reflection heavily, leading to runtime type errors.
  • Require verbose setup code.
  • Don’t fully leverage Go 1.18+ generics.

gs-mock solves these problems by providing compile-time safety and a much simpler API.


:sparkles: Key Features

  • Type-Safe: Built with Go generics, ensuring no runtime surprises.

  • Multiple Mocking Modes:

    • Handle: directly handle function calls.
    • When/Return: conditionally return results.
  • Flexible Matching: Supports up to 5 parameters and 5 return values.

  • Context Integration: Works seamlessly with context.Context.

  • Auto Reset: Easily reset all mocks with Manager.Reset().

  • Clear Errors: Detailed panic messages when mocks are missing or duplicated.


:rocket: Quick Example

type Repository[T any] interface {
    FindByID(id string) (T, error)
}

// Generated mock: RepositoryMockImpl[T]

func TestRepositoryMock(t *testing.T) {
    repo := NewRepositoryMockImpl[int](gsmock.NewManager())

    // Expect panic when no mock is registered
    assert.Panic(t, func() {
        _, _ = repo.FindByID("1")
    }, "no mock code matched")

    // Register behavior
    repo.MockFindByID().Handle(func(id string) (int, error) {
        return 42, nil
    })

    v, err := repo.FindByID("1")
    assert.Nil(t, err)
    assert.Equal(t, v, 42)
}

:gear: Installation

gs-mock comes with a code generation tool:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/go-spring/gs/HEAD/install.sh)"

Then in your code:

//go:generate gs mock -o service_mock.go

:open_file_folder: GitHub

:backhand_index_pointing_right: https://github.com/go-spring/gs-mock

I’d love feedback, contributions, and real-world testing reports.
Feel free to open issues or PRs if you find something missing!

Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.