侦听调用Golang中另一个结构使用的结构函数[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

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

type A struct {

}

func (a *A) Foo (){}

type B struct {
    a *A
}

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

我基本上想要检查调用Bar时确实调用了Foo

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

go mocking
1个回答
0
投票

如果你想测试B并查看它是否真的调用A的Foo函数,你需要模拟出A对象。由于您要检查的函数是Foo,只需创建一个简单的Fooer接口(在Go中称之为函数加上'er'),只使用该函数。用B替换B对A的引用,你就是好人。我根据你的代码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")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.