首页 > 解决方案 > go - 如何在测试用例中模拟结构的方法调用

问题描述

这是结构及其方法的示例代码

type A struct {}

func (a *A) perfom(string){
...
...
..
} 

然后我想从invoke()位于包外的函数中调用该方法,示例代码

var s := A{}
func invoke(url string){
   out := s.perfom(url)
   ...
   ...
} 

invoke我想通过模拟performA的方法来编写函数的测试用例。

在java中,我们有mockito、jmock框架来存根方法调用。

有什么办法,我们可以在不引入interfaces源代码的情况下模拟结构的方法调用吗?

标签: unit-testinggomocking

解决方案


要模拟方法调用,您需要模拟您的结构。

使用您提供的代码示例,我建议您制作一个Performer实现您的Perform调用的接口。您的真实结构和模拟结构都将实现此接口。

我还建议将您的结构作为参数传递给调用函数,而不是使用全局变量。

这是一个例子:

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()
}

在您的测试中,将模拟注入到您的invoke调用中。在您的真实代码中,将真实结构注入到您的invoke调用中。

使用像https://godoc.org/github.com/stretchr/testify/mock这样的库,你甚至可以很容易地验证你的方法是用正确的参数调用的,调用了正确的次数,并控制模拟的行为。


推荐阅读