如何对执行过程进行测试
时间:2024-03-12
浏览:195
作者:佚名
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《如何对执行过程进行测试》,聊聊,我们一起来看看吧!
问题内容
此代码正在执行二进制命令并返回 std.out 和 std.error
func exe(bin string, args string, path string) (string, error string) {
cmd := exec.command(bin, strings.split(args, " ")...)
cmd.dir = path
stdoutbuf := &bytes.buffer{}
cmd.stdout = stdoutbuf
stderrbuf := &bytes.buffer{}
cmd.stderr = stderrbuf
cmd.run()
return stdoutbuf.string(), stderrbuf.string()
}
问题是我不知道如何对其进行良好的测试,每个系统都将支持它 例如如果我尝试运行“echo”命令,测试会在 darwin 和 linux 上运行,但不会在 windows 上运行。我应该怎么做?
func Test_execute(t *testing.T) {
type args struct {
bin string
args string
path string
}
tests := []struct {
name string
args args
wantString string
wantError string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotString, gotError := exe(tt.args.bin, tt.args.args, tt.args.path)
if gotString != tt.wantString {
t.Errorf("exe() gotString = %v, want %v", gotString, tt.wantString)
}
if gotError != tt.wantError {
t.Errorf("exe() gotError = %v, want %v", gotError, tt.wantError)
}
})
}
}
我搜索了一下,发现了这个, https://www.joeshaw.org/testing-with-os-exec-and-testmain/ 但现在确定如何将环境与我的测试结合起来......
解决方案
使用 go 构建标签或文件名。例如,对于 linux 和 windows:
a_linux_test.go(linux 文件名):
package main
import "testing"
func testlinuxa(t *testing.t) {
t.log("linux a")
}
l_test.go(linux 构建标记):
// +build linux
package main
import "testing"
func testlinuxl(t *testing.t) {
t.log("linux l")
}
a_windows_test.go(windows 文件名):
package main
import "testing"
func testwindowsa(t *testing.t) {
t.log("windows a")
}
w_test.go(windows 构建标记):
// +build windows
package main
import "testing"
func testwindowsw(t *testing.t) {
t.log("windows w")
}
输出(在 linux 上):
$ go test -v
=== run testlinuxa
--- pass: testlinuxa (0.00s)
a_linux_test.go:6: linux a
=== run testlinuxl
--- pass: testlinuxl (0.00s)
l_test.go:8: linux l
pass
$
输出(在 windows 上):
>go test -v
=== RUN TestWindowsA
--- PASS: TestWindowsA (0.00s)
a_windows_test.go:6: Windows A
=== RUN TestWindowsW
--- PASS: TestWindowsW (0.00s)
w_test.go:8: Windows W
PASS
>
参考文献:
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
