如何验证特定函数是否被调用

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

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.

huangapple
  • 本文由 发表于 2015年9月7日 00:08:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/32425558.html
匿名

发表评论

匿名网友

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

确定