Testing Commands with Mock Resources

So far, we’ve been testing the external commands by executing them directly. This is a perfectly valid approach. But sometimes it’s not desirable or possible to execute a command directly on the machine where we’re testing the code. For these cases, we’ll mock the external commands by using Go function during tests. This approach also allows us to use Go code to simulate abnormal conditions, such as timeouts, which are harder to simulate using external services. Go’s standard library applies this approach to test the function from the os/exec package. For more information, check the source code for the exec_test.go file from the standard library.

Write a test function

To use this approach, we’ll write a test function that replaces the function exec.CommandContext() from the exec package that we use to create the exec.Cmd type during tests. First, we edit the file timeoutStep.go and add a package variable command, assigning the original function exec.CommandContext():

Get hands-on with 1200+ tech skills courses.