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

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

DDD
DDDOriginal
2024-12-08 00:09:12731browse

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

Mocking Method Calls of Structs in Go Test Cases Without Interfaces

In Go, there is no direct equivalent to frameworks like Mockito and jMock for mocking method calls of structs. However, there are several techniques that can be employed to achieve a similar level of mocking without introducing interfaces in the source code.

One approach involves creating a mock struct that implements the same methods as the original struct. The mock struct can then be injected into the function or method that needs to be tested, allowing you to control the behavior and verify the calls.

Consider the following example:

type A struct {}

func (a *A) perform(url string){
    // ...
} 

func invoke(s A, url string){
    out := s.perform(url)
    // ...
} 

To mock the method call of perform, you can create a mock struct AMock that implements the same interface as A.

type AMock struct {}

func (a *AMock) perform(url string) {
    // mocked implementation
}

In your test case, you can inject the mock struct into the invoke function and assert the expected behavior.

Another approach is to use a dependency injection framework like testify/mock. This framework provides a set of extension methods that allow you to mock interfaces and verify their usage in your test cases.

import "github.com/stretchr/testify/mock"

type A struct {}

type AMock struct {
    mock.Mock
}

func (a *AMock) perform(url string){
    a.Called(url)
} 

func invoke(s *A, url string){
    // ...
} 

By using the testify/mock framework, you can easily create mocks, verify method calls, and set expectations for your test cases.

The above is the detailed content of How to Mock Struct Method Calls in Go Tests Without Using 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