监听调用 Golang 中另一个结构使用的结构函数

所以我是 Golang 中模拟结构和函数的初学者。我基本上想检查是否已为单元测试目的调用了一个函数。这是代码:

type A struct {

}func (a *A) Foo (){}type B struct {
    a *A
}func (b* B) Bar () {
    a.Foo()
}

我基本上想检查在调用 Bar 时是否确实调用了 Foo

我知道有一些可用于 Golang 的模拟框架,但在测试现有结构和结构方法时它们非常复杂


小唯快跑啊
浏览 92回答 1
1回答

烙印99

如果你想测试B,看看它是否真的调用了A的Foo函数,你需要模拟出A对象。由于您要检查的函数是Foo,只需创建一个仅包含该函数的简单Fooer接口(这就是您在 Go 中所称的函数加上 'er')。将 B 对 A 的引用替换为对 Fooer 的引用,就可以了。我在 Go Playground 上根据您的代码创建了一个小示例:package mainimport "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")    }}
打开App,查看更多内容
随时随地看视频慕课网APP