Home >Backend Development >Golang >How to Mock Struct Method Calls in Go Tests Without Interfaces?

How to Mock Struct Method Calls in Go Tests Without Interfaces?

Susan Sarandon
Susan SarandonOriginal
2024-12-09 18:57:26375browse

How to Mock Struct Method Calls in Go Tests Without Interfaces?

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:

  1. Create a Performer interface that defines the method to be mocked.
  2. Create a real implementation A of the Performer interface.
  3. Create a mock implementation AMock of the Performer interface.
  4. Pass the mock implementation to the invoke function in the test case.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn