Mocking Struct Methods in Go Test Cases
In Go, mocking method calls of a struct can be achieved without introducing interfaces into the source code. Here's how:
Mocking a Sample Struct and Method
Consider the following struct and method:
type A struct {} func (a *A) perfom(string){ ... ... .. }
Mocking in Test Cases
To mock the perform method for test cases:
type Performer interface { perform(string) }
type AMock struct {} func (a *AMock) perform(string) { // Mocked behavior } type A struct {} func (a *A) perform(string) { // Real implementation }
func invoke(url string, p Performer) { out := p.perfom(url) ... ... }
func TestInvokeWithMock(t *testing.T) { var amok = &AMock{} invoke("url", amok) // Verify mock behavior (e.g., assert it was called with the correct argument) }
func TestInvokeWithReal(t *testing.T) { var a = &A{} invoke("url", a) // No need for verification since it's the real implementation }
Other Options
Libraries like [testify/mock](https://godoc.org/github.com/stretchr/testify/mock) provide even more robust mocking capabilities, allowing you to control mock behavior and verify method calls.
The above is the detailed content of How to Mock Struct Methods in Go Test Cases Without Interfaces?. For more information, please follow other related articles on the PHP Chinese website!