Home >Backend Development >Golang >How to Mock Struct Methods in Go Test Cases Without Interfaces?

How to Mock Struct Methods in Go Test Cases Without Interfaces?

DDD
DDDOriginal
2024-12-20 17:52:10642browse

How to Mock Struct Methods in Go Test Cases Without Interfaces?

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:

  1. Create a Mock Interface: Define an interface that represents the method to be mocked.
type Performer interface {
    perform(string)
}
  1. Create Mock and Real Implementations: Implement the interface for both a mock and a real implementation of the struct.
type AMock struct {}

func (a *AMock) perform(string) {
    // Mocked behavior
}

type A struct {}

func (a *A) perform(string) {
    // Real implementation
}
  1. Use Dependency Injection: Pass the mocked or real implementation as an argument to the function under test.
func invoke(url string, p Performer) {
    out := p.perfom(url)
    ...
    ...
}
  1. Inject Mock in Tests: In your test cases, inject the mock implementation into the invoke function.
func TestInvokeWithMock(t *testing.T) {
    var amok = &AMock{}
    invoke("url", amok)
    // Verify mock behavior (e.g., assert it was called with the correct argument)
}
  1. Inject Real Implementation in Production Code: In your production code, inject the real implementation of the struct into the invoke function.
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!

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