How to mock exec.Command in Go
In some of my projects we have code that needs to run external executables, and it’s very difficult to test them, especially when your function is based on some kind of stdout parcing. So how to mock these commands in Go? Let’s check how this goal is achieved in os/exec package. In exec_test.go we can see a helperCommand
. When running go tests, the go tool compiles an executable from your code, runs it and passes all the flags. Thus, while your tests are running, os.Args[0]
is the name of the test executable. So the executable is already there and runnable, by definition.
Let’s mock our function to get git rev-parse HEAD
.
|
|
I use a Commander
interface with CombinedOutput
function that accepts command string and multiple arguments.
|
|
And now we need 2 implementations of this interface.
|
|
|
|
You may find something strange in TestCommander
, but as I explained before, this function builds up a command to run the current test file and run the TestOutput
function passing along all the args you originally sent. This lets you do things like return different output for different commands you want to run.