【问题标题】:Listen To call on a struct function used by another struct in Golang [duplicate]听调用Golang中另一个结构使用的结构函数[重复]
【发布时间】:2018-08-31 04:19:18
【问题描述】:

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

type A struct {

}

func (a *A) Foo (){}

type B struct {
    a *A
}

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

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

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

【问题讨论】:

    标签: go mocking


    【解决方案1】:

    如果你想测试 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")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-12
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多