dongnai6973
2015-09-06 16:08
浏览 79
已采纳

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

Currently 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. (The way I would in Java using Mockito). Can anyone help me write this test for I am not quite sure what the current available answers on the internet mean. They're suggesting the use of interfaces.

Currently the Feature-struct only contains a string Cmd.

图片转代码服务由CSDN问答提供 功能建议

目前,我正在尝试用Go编写TDD。 但是,我受困于以下内容。

要编写的测试:

  func TestFeatureStart(t * testing.T){
  
} 
   
 
 

要测试的实施:

  func(f * Feature)Start()error {\  n cmd:= exec.Command(f.Cmd)
 cmd.Start()
} 
   
 
 

如何测试这个简单的位。 我认为我只想验证exec-library是否正确。 (我在Java中使用Mockito的方式)。 谁能帮我编写此测试,因为我不太确定互联网上当前可用的答案是什么意思。 他们建议使用接口。

当前,Feature-struct仅包含字符串Cmd。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtwknzk3764 2015-09-06 18:05
    已采纳

    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.

    点赞 打赏 评论

相关推荐 更多相似问题