Golang: Using an InMemory MongoDB for Unit Testing with Transactions
Short story behind ‘strikememongo’
As we started developing Strike, we knew that as a cybersecurity company, we needed to provide a service that was secure and reliable. This is why we prioritize unit testing, and while using MongoDB with transactions, we discovered there was no way to create tests with an in memory service that was self contained and run only while testing plus supporting transactions.
In the beginning, we started by using a MongoDB instance with a replica set online, but that increased our testing time significantly. For that reason, we decided to design our own library, one that would spin up an InMemory MongoDB instance for tests and make it have a replica set so our transactions can truly be tested. We have now made strikememongo available and this is what I will be using in this brief tutorial, hope it helps :)
Hands On
First of all, let’s set up our tutorial scenario: We are going to have a client, a promotion and a room. Once our client has purchased a room hotel, we are going to add it to our clients, set up a new promotion, and a new room allocation. Thus, we will affect ‘clients’, ‘promotions’ and ‘rooms’ collections.
Following, we create the function that will perform these inserts in our database. As we don’t want to have our database corrupted, if an error occurs while inserting the new room, we want the entire operation to roll back; we can easily achieve this by using transactions.
After our function is ready, we develop the unit test. In this case, we are going to be using our InMemory and ephemeral MongoDB server.
First, let’s create our setup and cleanup functions. The most importan thing, will be our TestMain function, as here we need to spin up the mongoDB server before creating the collections and inserting items.
Finally, we are going to develop our test which will consist in adding a client and checking it has been added to ‘clients’ database and a room has been created.
After having run the test, the result displayed should be something similar to:
ok github.com/strikesecurity/medium-test-tutorial/repositoriestests
Conclusion
We have just seen how we can develop a unit test and support MongoDB transactions, which otherwise will only be possible by using a remote instance.
If you want to use it in your own projects, you just need to install it by running ‘go get -u github.com/strikesecurity/strikememongo’ and add it to your go module.
You can have a look at https://github.com/strikesecurity/strikememongo for some examples or check the GoDoc.
Will be happy to help you if any doubt arises, just reach out here or in LinkedIn, thanks for reading!
Cheers from Strike ;)