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.Command
which allows you to execute an external command to the processcmd.StdoutPipe
which returns us a io.ReadCloser
(this will become important)io.ReadCloser
and then we Start
the 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 Payload
struct.msg.xml
strings.ToUpper
on the <message>
)io.ReadCloser
. We can use this existing abstraction to separate concerns and make our code testable.TestGetData
can act as our integration test between our two concerns so we'll keep hold of that to make sure it keeps working.GetData
takes its input from just an io.Reader
we 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.GetData
.