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

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-struct 只包含一个字符串 Cmd。

您可以伪造整个接口,但也可以使用可伪造的函数。代码中:

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("command didn't start")
}

另请参阅:Andrew Gerrand 的 Testing Techniques talk