如何在测试用例中模拟结构的方法调用 [英] How to mock a method call of a struct in test case at go

查看:77
本文介绍了如何在测试用例中模拟结构的方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is the sample code for the struct and its method

type A struct {}

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

然后我想从驻留在程序包外部的函数invoke()(示例代码)中调用该方法

Then i want to call the method from the function invoke() residing outside the package, sample code

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

我想通过模拟A的perform方法来编写功能invoke的测试用例.

I want to write the test case for the function invoke by mocking the perform method of A.

在Java中,我们有mockito,jmock框架来存根方法调用.

In java, we have mockito, jmock framework to stub method calls.

有什么办法吗,我们可以模拟结构体的方法调用而无需在源代码中引入interfaces吗?

Is there any way in go, we can mock the method call of the struct without introducing interfaces in source code ?

推荐答案

要模拟方法调用,您需要对结构进行模拟.

To mock a method call, you need to make a mock of your structure.

对于您提供的代码示例,我建议创建一个实现您的Perform调用的Performer接口.您的真实结构和模拟结构都将实现此接口.

With the code example you provided, I would recommend making a Performer interface that implements your Perform call. Both your real structure and your mock structure would implement this interface.

我还建议您将结构作为参数传递给invoke函数,而不要使用全局变量.

I would also recommend passing your structure as an argument to the invoke function instead of using a global variable.

这里是一个例子:

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调用.

In your tests, inject the mock to your invoke call. In your real code, inject the real structure to your invoke call.

使用类似> https://godoc.org/github.com/stretchr的库/testify/mock ,您甚至还可以真正轻松地验证使用正确的参数(正确的次数)调用了您的方法,并控制了模拟的行为.

Using a library like https://godoc.org/github.com/stretchr/testify/mock you will even be able to really easily verify that your method is called with the right arguments, called the right amount of times, and control the mock's behavior.

这篇关于如何在测试用例中模拟结构的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆