如何在 testify 中模拟一个空函数?
时间:2024-02-05
浏览:369
作者:佚名
在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《如何在 testify 中模拟一个空函数?》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!
问题内容我目前正在对一段代码进行单元测试,该代码使用的接口包含没有输入或输出的方法。使用testify的mock包,编写该函数的mock实现的正确方法是什么?
目前,我将其写为:
type A struct {
mock.Mock
}
func (a *A) DoSomething() {
_ = a.Called(nil)
}
正确答案
假设你有这样的东西:
package foo
type Foo struct {}
func New() *Foo {
return &Foo{}
}
func (f *Foo) Called() {
fmt.Println("no in/output, does something here")
}
package bar
type Dependency interface {
Called() // the dependency you want to make sure is called
}
type Svc struct {
dep Dependency
}
func New(d Dependency) *Svc {
return &Svc{
dep: d,
}
}
func (s *Svc) Something() {
s.dep.Called()
}
现在,使用我的相关答案中概述的mockgen,我们可以添加以下内容:
package bar
//go:generate go run github.com/golang/mock/mockgen -destination mocks/deps_mock.go -package mocks your.mod/path/to/pkg/bar Dependency
type Dependency interface {
Called() // the dependency you want to make sure is called
}
type Svc struct {
dep Dependency
}
func New(d Dependency) *Svc {
return &Svc{
dep: d,
}
}
func (s *Svc) Something() {
s.dep.Called()
}
这将在 bar 下生成一个包(如 bar/mocks),其中包含您要在测试中使用的生成的模拟/假/间谍对象,如下所示:
package bar_test
import (
"testing"
"your.mod/path/to/bar"
"your.mod/path/to/bar/mocks"
"github.com/golang/mock/gomock"
)
func TestSomething(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish() // this is when the expected calls are checked
dep := mocks.NewMockDependency(ctrl) // create the instance of the mock/spy
svc := bar.New(dep) // pass in the spy
dep.EXPECT().Called().Times(1)
svc.Something() // the test will pass if the call was made
// alternatively, you can log some output, too:
dep.EXPECT().Called().Times(1).Do(func() {
// this gets called as though it was s.Called() in your code
t.Log("The dependency was called as expected")
})
svc.Something()
}
mockgen/gomock 的功能远不止于此,请在此处了解更多相关信息。似乎该存储库最近已存档并移动,我怀疑 其替代品 几乎是一个下降不过,在替换中+一些新功能。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.27
11.27
热门专题
