Skip to content

Conversation

@ktsivkov
Copy link

@ktsivkov ktsivkov commented Oct 3, 2025

Summary

type ExampleFuncType func(string) error

type SomeService struct {
	Func ExampleFuncType
}

func (s *SomeService) Do(x string) error {
	return s.Func(x)
}

func TestSomeService(t *testing.T) {
	var typ ExampleFuncType
	fn, err := FuncMockFor(typ)
	if err != nil {
		panic(err)
	}

	given := "test"
	expectedErr := errors.New(given)
	fn.On("test").Return(expectedErr)
	defer fn.AssertExpectations(t)

	service := &SomeService{
		Func: fn.Build().(ExampleFuncType),
	}
	assert.ErrorIs(t, service.Do(given), expectedErr)
}

Changes

Introduced a FuncMock type that consolidates the logic of function mocking and wraps around the default mocker. Added tests to cover.

Motivation

It happens for me to often inject functions as dependencies, since I use this package extensively would love the idea to have a mock builder for functions that builds on the already awesome API provided by this package.
I have found a way how to implement it in an elegant and simple fashion. Made it work with Go 1.17, but it can be even cleaner on higher versions since Generics and you could do something like reflect.TypeFor[T]. Nevertheless this version is also nice.

Related issues

N/A

@dolmen dolmen added enhancement pkg-mock Any issues related to Mock enhancement: extend API An enhancement that grows the API surface labels Oct 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement: extend API An enhancement that grows the API surface enhancement pkg-mock Any issues related to Mock

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants