此代码正在执行二进制命令,并返回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/ 但是现在确定如何将环境与我的测试结合起来...
答案 0 :(得分:2)
使用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
>
参考文献: