Sobes.tech
Junior — Middle

What libraries have you used for creating mock objects in testing?

sobes.tech AI

Answer from AI

In Go, the following libraries are often used for creating mock objects in testing:

  • gomock — the official library from Google, allows generating mocks based on interfaces using the mockgen tool.
  • testify/mock — part of the popular testify package, provides a convenient way to create mocks with the ability to set expectations and verify calls.

Example of using testify/mock:

import (
    "testing"
    "github.com/stretchr/testify/mock"
)

type MyInterface interface {
    DoSomething(int) string
}

type MyMock struct {
    mock.Mock
}

func (m *MyMock) DoSomething(i int) string {
    args := m.Called(i)
    return args.String(0)
}

func TestMyFunction(t *testing.T) {
    m := new(MyMock)
    m.On("DoSomething", 123).Return("result")

    res := m.DoSomething(123)
    if res != "result" {
        t.Errorf("unexpected result: %s", res)
    }

    m.AssertExpectations(t)
}

These libraries help isolate the code under test from external dependencies and verify interactions with them.

What libraries have you used for creating mock… - sobes.tech