使用未公开接口作为参数的 Gomock
时间:2024-02-12
浏览:109
作者:佚名
本篇文章向大家介绍《使用未公开接口作为参数的 Gomock》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。
问题内容
我正在使用 gomock (源模式)并希望模拟一段如下所示的代码:
type foo interface {
methoda() int
}
type boo interface {
methodb(f foo) string
}
其中未导出的 foo 接口用作 methodb() 中的参数。使用mockgen后,模拟的methodb()看起来像:
func (m &MockBoo) MethodB(f foo) string { ... }
这是错误的,因为 foo 未导出且无法访问。
想知道是否有解决方法(例如,将 foo 改为 mockfoo 作为参数)?
reflect 模式,但也有同样的问题。正确答案
要测试私有类型,请在与该类型相同的包中声明您的测试。这样做将允许您访问私有符号。
示例
测试
package foo
import (
"testing"
"github.com/golang/mock/gomock"
)
func testname(t *testing.t) {
con := gomock.newcontroller(t)
defer con.finish()
boo := newmockboo(con)
var f foo
boo.expect().methodb(f)
if len(boo.methodb(f)) > 0 {
t.fail()
}
}
生成模拟
$ mockgen -source=foo.go -package foo -destination foo_mock.go
foo.go
package foo
type foo interface {
methoda() int
}
type boo interface {
methodb(f foo) string
}
运行测试:
$ go test -v === RUN TestName --- PASS: TestName (0.00s) PASS ok foo 0.001s
以上就是《使用未公开接口作为参数的 Gomock》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
热门专题
