英文:
How to verify if a specific function is called
问题
我正在尝试使用Go语言编写TDD(测试驱动开发)代码。然而,我在以下部分遇到了困难。
要编写的测试代码:
func TestFeatureStart(t *testing.T) {}
要测试的实现代码:
func (f *Feature) Start() error {
cmd := exec.Command(f.Cmd)
cmd.Start()
}
如何测试这个简单的代码片段呢?我想我只需要验证exec库是否被正确调用。在Java中,我会使用Mockito来实现这个功能。有人可以帮我编写这个测试吗?根据我所了解的,建议使用接口来实现。
Feature结构体只包含一个字符串Cmd。
英文:
I'm trying my hand at writing TDD in Go. I am however stuck at the following.
The test to write:
func TestFeatureStart(t *testing.T) {}
Implementation to test:
func (f *Feature) Start() error {
cmd := exec.Command(f.Cmd)
cmd.Start()
}
How would one test this simple bit? I figured I only wanted to verify that the exec library is spoken to correctly. That's the way I would do it in Java using Mockito. Can anyone help me write this test? From what I've read the usage of interfaces is suggested.
The Feature-struct only contains a string Cmd.
答案1
得分: 19
你可以通过接口来伪造整个交易,但也可以使用可伪造的函数。在代码中:
var cmdStart = (*exec.Cmd).Start
func (f *Feature) Start() error {
cmd := exec.Command(f.Cmd)
return cmdStart(cmd)
}
在测试中:
called := false
cmdStart = func(*exec.Cmd) error { called = true; return nil }
f.Start()
if !called {
t.Errorf("命令未启动")
}
另请参阅:Andrew Gerrand的Testing Techniques talk。
英文:
You can fake the whole deal with interfaces, but you could also use fakeable functions. In the code:
var cmdStart = (*exec.Cmd).Start
func (f *Feature) Start() error {
cmd := exec.Command(f.Cmd)
return cmdStart(cmd)
}
In the tests:
called := false
cmdStart = func(*exec.Cmd) error { called = true; return nil }
f.Start()
if !called {
t.Errorf("command didn't start")
}
See also: Andrew Gerrand's Testing Techniques talk.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论