英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论