英文:
Stubbing methods in Golang unit testing
问题
我整晚都在思考这个问题,但仍然找不到一种优雅的方法来解决这个问题。假设我有一个结构体:
type file struct {
x int
}
func (f *file) filename() string {
return fmt.Sprintf("%s/%d.log", exportPath, f.x)
}
func (f *file) write(data []byte) {
...
aFile = os.File.Open(f.filename())
...
}
现在我想测试write方法,并将filename方法存根化以返回临时文件名。我该如何做呢?目前我找到了两个选项:
- 声明
filename
为func(f *file)
,并在测试中进行重写。 - 将
filename
作为结构体的字段。
但在这种情况下,它们似乎都不正确。所以问题是 - 我能以任何方式存根化这个方法吗?而且一般来说 - 如何为测试存根化内部方法(对于外部方法,显然可以使用依赖注入)?
英文:
I've been thinking about this whole night, but still cannot find an elegant way to do this thing. Let's say I have a struct
type file struct {
x int
}
func (f *file) filename() string {
return fmt.Sprintf("%s/%d.log", exportPath, f.x)
}
func (f *file) write(data []byte) {
...
aFile = os.File.Open(f.filename())
...
}
Now I want to test write method and stub filename method to return temp filename. How can I do this? To the moment I found two options:
- declare filename = func(f* file) and override it in test
- make filename a field of the struct
But they both seem wrong in this case. So the question is - can I stub in any way this method? And in general - how to stub internal methods for testing (for external obviously dependency injection could work)
答案1
得分: 2
将文件名作为结构体的一个字段是一种优雅的方式。
在创建结构体时应该定义filename
。
type fileStruct {
filename string
}
func newFileStruct(x int) *fileStruct {
filename := fmt.Sprintf("%s/%d.log", exportPath, x)
return &fileStruct{filename: filename}
}
func (f *fileStruct) write(data []byte) {
...
file = os.File.Open(f.filename)
...
}
英文:
Making filename a field of the struct is an elegant way.
The filename
should be defined when new the struct.
type fileStruct {
filename string
}
func newFileStruct(x int) *fileStruct {
filename := fmt.Sprintf("%s/%d.log", exportPath, x)
return &fileStruct{filename: filename}
}
func (f *fileStruct) write (data []byte) {
...
file = os.File.Open(f.filename)
...
}
答案2
得分: 0
最终我将我的结构体完全可注入,代码看起来清晰简洁,测试也非常顺利!
英文:
Ended up making my structs 100% injectable, the code looks clear and concise and tests like a charm!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论