“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《调用 Golang 中结构体的嵌套结构体方法》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!
所以我是 golang 中模拟结构和函数的初学者。我基本上想检查是否已出于单元测试目的调用了函数。这是代码:
type A struct {
}
func (a *A) Foo (){}
type B struct {
a *A
}
func (b* B) Bar () {
a.Foo()
}
我基本上想检查当 bar 被调用时 foo 是否确实被调用
我知道 golang 有一些可用的模拟框架,但在测试现有结构和结构方法时它们非常复杂
解决方案
如果你想测试 b 并看看它是否真的调用了 a 的 foo 函数,你需要模拟 a 对象。由于您要检查的函数是 foo,因此只需创建一个仅包含该函数的简单 fooer 接口(这就是您在 go 中的调用方式,函数加“er”)。将 b 对 a 的引用替换为对 fooer 的引用,就可以了。我根据您的代码 here on the Go Playground 创建了一个小示例:
package main
import "testing"
type A struct {
}
func (a *A) Foo() {}
type Fooer interface {
Foo()
}
type B struct {
a Fooer
}
func (b *B) Bar() {
b.a.Foo()
}
func main() {
var a A
var b B
b.a = &a
b.Bar()
}
// in your test:
type mockFooer struct {
fooCalls int
}
func (f *mockFooer) Foo() {
f.fooCalls++
}
func Test(t *testing.T) {
var mock mockFooer
var bUnderTest B
bUnderTest.a = &mock
bUnderTest.Bar()
if mock.fooCalls != 1 {
t.Error("Foo not called")
}
}今天关于《调用 Golang 中结构体的嵌套结构体方法》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
