Sobes.tech
Junior — Middle

Milliseid teeke kasutasite mock-objektide loomiseks testimisel?

sobes.tech AI

Vastus AI-lt

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

  • gomock — Google's official library, 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 expectations and call verifications.

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 tested code from external dependencies and verify interactions with them.