Unit testing in Go

devils2ndself

Artem Tanyhin

Posted on November 11, 2022

Unit testing in Go

Hey there! Thanks for checking in again! This week, I've been trying to implement unit testing for my Open Source project SSGo. Let me tell you more about how I did it.

Gathering prerequisites

In my unit tests, I wanted to check HTML parsing capabilities of SSGo; however, my code was not structured properly for that.

HTML parsing was not enclosed in a separate function, rather it was a part of a big GenerateHTML function, which created needed files, read from existing files and generated HTML. I needed to first refactor the code a bit.

I separated ParseText and ParseMarkdown functions for parsing .txt and .md files respectively, which also allowed to fix a couple of bugs and inconsistencies in code.

Now, it was time to finally write some tests.

Choosing the testing tools

I saw a very interesting blog post regarding testing frameworks in Go, which helped me pick from a formed list.

It is very handy that Go has it's own built-in testing tool, which runs every file that ends with _test.go. It also allows for coverage reports and individual test runs.

All you have to do to run the tests is run go test <package_name> and that's it!

I also used github.com/stretchr/testify package for easier assertions using Equal function.

Tests I implemented

There is actually not much I could test before performing the refactoring of my code because almost every function had file i/o in it, which is not the best when dealing with unit tests.

So, after I refactored a part of my code, I made some tests for ParseText and ParseMarkdown general and edge cases.

I also made a couple of tests for GetNameAndExt function that separates the file name and its extension.

It was also important to document everything for coming developers, so I mentioned everything in CONTRIBUTING.md. Come check it out if you want :)

After I was done, I squashed all my commits into one and merged it to master.

💖 💪 🙅 🚩
devils2ndself
Artem Tanyhin

Posted on November 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Unit testing in Go
opensource Unit testing in Go

November 11, 2022