I am executing a command using os/exec.Command() which generated XML data. The command will be executed in a function called GetData().In order to test GetData(), I have some testdata which I created.In my _test.go I have a TestGetData which calls GetData() but that will use os.exec, instead I would like for it to use my testdata.What is a good way to achieve this? When calling GetData should I have a "test" flag mode so it will read a file ie GetData(mode string)?
exec.Commandwhich allows you to execute an external command to the process
cmd.StdoutPipewhich returns us a
io.ReadCloser(this will become important)
io.ReadCloserand then we
Startthe command and then wait for all the data to be read by calling
Wait. In between those two calls we decode the data into our
io.ReadCloser. We can use this existing abstraction to separate concerns and make our code testable.
TestGetDatacan act as our integration test between our two concerns so we'll keep hold of that to make sure it keeps working.
GetDatatakes its input from just an
io.Readerwe have made it testable and it is no longer concerned how the data is retrieved; people can re-use the function with anything that returns an
io.Reader(which is extremely common). For example we could start fetching the XML from a URL instead of the command line.