douchen5971 2018-08-30 20:06
浏览 46
已采纳

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

This question already has an answer here:

So I am a beginner with mocking struct and functions in Golang. I basically want to check if a function has been called for unit testing purpose. Here is the code:

type A struct {

}

func (a *A) Foo (){}

type B struct {
    a *A
}

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

I basically want to check that Foo is indeed called when Bar is called

I know there is some mock framework available for Golang but they are pretty complicated when it comes to testing existing struct and struct methods

</div>
  • 写回答

1条回答 默认 最新

  • dpgf42422 2018-08-30 20:19
    关注

    If you want to test B and see if it really calls A's Foo function, you need to mock out the A object. Since the function you want to check for is Foo, just create a simple Fooer interface (which is what you would call it in Go, the function plus 'er') with only that function. Replace B's reference to A with one to Fooer and you are good. I created a little sample based on your code 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")
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分