在Golang单元测试中存根方法

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

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方法存根化以返回临时文件名。我该如何做呢?目前我找到了两个选项:

  1. 声明filenamefunc(f *file),并在测试中进行重写。
  2. 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:

  1. declare filename = func(f* file) and override it in test
  2. 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!

huangapple
  • 本文由 发表于 2016年1月20日 13:50:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/34892455.html
匿名

发表评论

匿名网友

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

确定