Skip to content

Proposal: Provide concurrency-safe setter methods for function fields #231

Open
@sapuri

Description

@sapuri

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions