Testing Commands with Mock Resources

Powerful Command-Line Applications in Go — by Ricardo Gerardi (68 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Integration Tests with a Local G it Server | TOC | Handling Signals 👉

So far, you’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 you’re testing the code. For these cases, you’ll mock the external commands by using Go function during tests. This approach also allows you 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.[36]

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

processes/goci.v7/timeoutStep.go

​   ​return​ s
​ }

»​var​ command = exec.CommandContext
»

​ ​func​ (s timeoutStep) execute() (​string​, ​error​) {
​ ​return​ s.message, nil
​ }

Since functions are first class types in Go, you can assign them to variables and pass them as…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.