Integration test on golang using Docker
According to Wikipedia, the integration test is the phase in software testing, where you combine individual software modules and test them as a group. Integration tests are required to test if the software fulfills the specified functional requirement.
In this article, I am going to show you how to write integration tests. The code example provided here is written in go programming language but the concept is easily transferable to any other languages.
Let us set a premise first, here we are trying to publish and subscribe a message to and from rabbitmq
using amqp
protocol. We have two functions Publish
and Subscribe
. Publish
takes []byte
as an input. Subscribe
returns <-chan []byte
(channel of []byte
).
Let’s look at the code example:
Note: The Code example above is a wrapper around the amqp package. The purpose of the wrapper package is to hide complexity and expose a simpler API.
Now let’s look at the test file for the above code example:
Note: In the above code example, I have used a package called testify to create a test suite and run assertion easily.
We are done with go code, now let’s write Dockerfile
and docker-compose.yml
to run integration tests using Docker.
Dockerfile
is fairly simple. The only thing that I want to point out is CMD
instruction that uses a Makefile
target called integration-tests
. I will get back to the Makefile
in a while, for now, let’s look at the docker-compose.yml
file.
docker-compose.yml
file is also fairly simple. We have two services called tests
and rabbitmq
, tests
service depends upon rabbitmq
and both of these services are bound to a network called queue-test
.
Let’s look at Makefile
now:
The Makefile
target tests help us run integration tests and do clean up once we are done. I also want to point out flag --abort-on-container-exit
on command docker-compose up
this flag helps us terminate rabbitmq
once we are done running tests using docker-compose.yml
Now, look at the Makefile
target integration-tests
, something interesting is going with this command
sh -c “while ! curl -s http://rabbitmq:15672 > /dev/null; do echo waiting for 3s; sleep 3; done”
here rabbitmq
takes a few seconds to completely start-up; we wait for 3sec and check if rabbitmq
is up yet using curl
on the URL http://rabbitmq:15672
. If it’s up we go to the next command on target (that runs tests) else we again wait for 3sec.
Using tools like Docker and Make we can run integration tests on isolation and clean up after we are done testing our code. Using Docker to run tests also helps us be consistent across the local environment and CI/CD environment making it a lot easier to maintain our test suite. Thank you for reading, look at this Github repo to see the above snippets into action.