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
Release: 2024-12-09 18:57:26
Original
373 people have browsed it

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)
   ...
   ...
} 
Copy after login

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()
}
Copy after login

In the test case, inject the mock implementation into the invoke function:

func TestCallerMock(t *testing.T) {
    mock := &AMock{}
    caller(mock)
}
Copy after login

In the real code, inject the real implementation into the invoke function:

func RealInvoke(url string) {
    a := &A{}
    out := a.perform(url)
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template