Proposal: Provide concurrency-safe setter methods for function fields
- Dominant language
- Go
- Stars
- 2.2k
- Forks
- 135
- Avg merge
- 11d 6h
- Merged PRs (30d)
- 1
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:
```generate/generate.go
//go:generate moq -out generated.go . MyInterface
// MyInterface is a test interface.
type MyInterface interface {
One() bool
}
```
After generation, we could have something like:
```generate/generated.go
// ...
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.
Contributor guide
No contributing guide indexed for this repository
Research direction
Start in generate/generate.go and inspect how generated.go currently declares function fields for interface methods. Compare the requested SetOneFunc example with the generator's output, then verify that generated mocks provide concurrency-safe setters and that concurrent reassignment is race-free.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- go
- Domain
- testing, tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100