exec.Command()
を使用するユニットテスト機能を覚えました。すなわち、exec.Command()
を嘲笑します。私は、より多くのユニットケースを追加して行きましたが、さまざまなシナリオで出力をモックできないという問題にぶつかっていました。ここでGo langでexec.Commandを複数の単体テストでモックする方法は?
は以下
package main
import (
"fmt"
"os/exec"
)
var execCommand = exec.Command
func printDate() ([]byte, error) {
cmd := execCommand("date")
out, err := cmd.CombinedOutput()
return out, err
}
func main() {
fmt.Printf("hello, world\n")
fmt.Println(printDate())
}
が
package main
import (
"fmt"
"os"
"os/exec"
"testing"
)
var mockedExitStatus = 1
var mockedDate = "Sun Aug 20"
var expDate = "Sun Aug 20"
func fakeExecCommand(command string, args ...string) *exec.Cmd {
cs := []string{"-test.run=TestHelperProcess", "--", command}
cs = append(cs, args...)
cmd := exec.Command(os.Args[0], cs...)
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
return cmd
}
func TestHelperProcess(t *testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
return
}
// println("Mocked Data:", mockedDate)
fmt.Fprintf(os.Stdout, mockedDate)
os.Exit(mockedExitStatus)
}
func TestPrintDate(t *testing.T) {
execCommand = fakeExecCommand
defer func() { execCommand = exec.Command }()
out, err := printDate()
print("Std out: ", string(out))
if err != nil {
t.Errorf("Expected nil error, got %#v", err)
}
if string(out) != expDate {
t.Errorf("Expected %q, got %q", expDate, string(out))
}
}
func TestPrintDateUnableToRunError(t *testing.T) {
execCommand = fakeExecCommand
defer func() { execCommand = exec.Command }()
mockedExitStatus = 1
mockedDate = "Unable to run date command"
expDate = "Unable to run date command"
out, err := printDate()
print("Std out: ", string(out))
if err != nil {
t.Errorf("Expected nil error, got %#v", err)
}
if string(out) != expDate {
t.Errorf("Expected %q, got %q", expDate, string(out))
}
}
go test
がために失敗した...テストコードhello_test.go
です...私はテストしようとしているサンプルコードhello.go
です第2の試験TestPrintDateUnableToRunError
...
$ go test hello
Std out: Sun Aug 20Std out: Sun Aug 20--- FAIL: TestPrintDateTomorrow (0.01s)
hello_test.go:62: Expected "Unable to run date command", got "Sun Aug 20"
FAIL
FAIL hello 0.017s
グローバルmockedDate
の値をテストケース内に設定しようとしても、初期化されたグローバル値は引き続き取得されています。 グローバル値は設定されていませんか?または、グローバル変数への変更がTestHelperProcess
に更新されていませんか?
...例として、私だけで使用される日付、ここで尋ねるために...おかげで私は実際にいくつかのスクリプトを呼び出ししようとしていた、そしてそのスクリプトは時々存在していない可能性があります。ところで 私は後でENV変数を利用してそれを行うことができることに気付きました。 – abhijithda