英文:
How to test system commands in go
问题
给定我有一个函数:
func getTotalMemory() string {
out,_ := exec.Command("grep", "MemTotal", "/proc/meminfo").Output()
t := strings.Split(string(out), ":")
x := strings.TrimSpace(t[1])
return x
}
我该如何编写一个测试函数来确保我正确解析了它?在 Ruby 中,我只需要做类似这样的事情:
os.expects(:Command).and_returns("string")
我目前正在使用 GoConvey,如果这对答案有任何影响,请告诉我。
谢谢!
英文:
Given I have a function like:
func getTotalMemory() string {
out,_ := exec.Command("grep", "MemTotal", "/proc/meminfo").Output()
t := strings.Split(string(out), ":")
x := strings.TrimSpace(t[1])
return x
}
How can I write a test for that function to make sure I'm parsing it properly? In ruby I would just do something like
os.expects(:Command).and_returns("string")
I'm currently using GoConvey if that has any impact on answers.
Thanks!
答案1
得分: 4
你可以从查看 os.exec
包的测试策略 开始:
请参考“src/pkg/os/exec/exec_test.go
”。
注意:GoConvey 与标准的 Go 测试框架兼容,所以这不会对你想要进行的测试类型产生任何影响。
英文:
You could start by looking at the test policy for os.exec
package:
see "src/pkg/os/exec/exec_test.go
".
Note: GoConvey is compatible with standard Go testing framework, so that won't have any bearing on the kind of test you want to do.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论