如何测试调用自己方法的结构体?

huangapple go评论71阅读模式
英文:

How to test a struct that calls its own method?

问题

我有一个结构体:

type foo struct {
    bar mockableInterface // 一个可以模拟的接口
}

func (f *foo) DoSmth1() []interface{} {
    return f.bar.Bar()
}

func (f *foo) DoSmth2() []interface{} {
    res := f.DoSmth1()
    // 一些用于测试的代码
}

在这里,我没有问题可以模拟bar和测试DoSmth1()。但是如何测试DoSmth2()并不明显。
我应该重写这个方法使其可测试,还是以某种方式重写测试?

英文:

I have a struct:

type foo struct {
    bar mockableInterface // some interface that I can mock
}

func (f *foo) DoSmth1() []interface{} {
    return f.bar.Bar()
}

func (f *foo) DoSmth2() []interface{} {
    res := f.DoSmth1()
    //some code to test
}

Here I have no problem with mocking bar and testing DoSmth1(). But it's not obvious how to test DoSmth2().
Should I rewrite this method to make it testable or rewrite tests somehow?

答案1

得分: 1

@mkopriva建议在DoSmth2()的测试中只是模拟Bar()的调用。但在这种情况下,每次DoSmth1()发生变化时,我都需要重写调用DoSmth1()的所有方法的测试。所以我想到了以下解决方案。我们可以将这个模拟逻辑封装在一个方法中:

func (s *TestSuite) ExpectDoSmth1(times int, in, out []interface{}) {
    s.barMock.Expect().Bar(in...).Times(times).Return(out...)
}

这样,如果DoSmth1()的实现发生变化,我们只需要修改这个方法,而它的API保持不变。

英文:

@mkopriva recommended just to mock Bar() call in DoSmth2() test. But in this case I would rewrite tests for all method that calls DoSmth1() every time it changes. So I've come to the following solution. We can encapsulate this mock logic in one method:

func (s *TestSuite) ExpectDoSmth1(times int, in, out []interface{}) {
    s.barMock.Expect().Bar(in...).Times(times).Return(out...)
}

This way we can change only this method if DoSmth1() implementation changes, till its API stays the same

huangapple
  • 本文由 发表于 2022年3月9日 22:49:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/71411222.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定