Mocking Method Calls of Structs in Go Test Cases
Problem:
How to mock a method call of a struct in a Go test case without introducing interfaces in the source code?
Code Example:
type A struct {} func (a *A) perfom(string){ ... ... .. } var s := A{} func invoke(url string){ out := s.perfom(url) ... ... }
Answer:
To mock a method call of a struct, one approach is to use a mock object.
Solution with Mock Object:
Example Code:
type Performer interface { perform() } type A struct {} func (a *A) perform() { fmt.Println("real method") } type AMock struct {} func (a *AMock) perform () { fmt.Println("mocked method") } func caller(p Performer) { p.perform() }
In the test case, inject the mock implementation into the invoke function:
func TestCallerMock(t *testing.T) { mock := &AMock{} caller(mock) }
In the real code, inject the real implementation into the invoke function:
func RealInvoke(url string) { a := &A{} out := a.perform(url) }
The above is the detailed content of How to Mock Struct Method Calls in Go Tests Without Interfaces?. For more information, please follow other related articles on the PHP Chinese website!