Open
Description
There are cases where we want to dynamically change the behavior of a mock method during testing. By default, moq generates a field like MyMethodFunc func(...)
for each interface method, and we can reassign the function pointer in our tests. However, this often leads to data races when multiple goroutines are running (especially in parallel tests).
So, how about generating concurrency-safe setter methods (using RWMutex) for each generated function pointer? For example:
//go:generate moq -out generated.go . MyInterface
// MyInterface is a test interface.
type MyInterface interface {
One() bool
}
After generation, we could have something like:
// ...
func (mock *MyInterfaceMock) SetOneFunc(f func() bool) {
mock.lockOneFunc.Lock()
defer mock.lockOneFunc.Unlock()
mock.OneFunc = f
}
// ...
With this approach, tests can safely change the mock function at runtime without causing data races.
Metadata
Metadata
Assignees
Labels
No labels