Writing unit tests in Golang Part3: Test suite

Siraphob K.
Nerd For Tech
Published in
3 min readSep 20, 2021

As you may know, a program usually grows and evolves over time. And as time advances, you may add new features, some edge cases handling, fixing bugs, etc. It is inevitable to add more tests as well. We can say that test cases are increasing along with the evolvement of the software.

https://www.getyarn.io/yarn-clip/70db0a71-520c-451b-9901-4f264e7d6b08

At some point, you will notice that “Crap, there’re a lot of tests and I don’t know which one I have to execute!”. When there’re way too many tests in your software, it could be cumbersome to manage them. (You can’t just execute all tests all the time whenever you push your code to git.) Sometimes, you just wanna test some functions of the program to assure that nothing breaks. This is where a test suite comes in.

A set of test cases is called a test suite. We can use a test suite to categorize tests into groups. For example, you can create a test suite for functional tests and performance tests. When you develop a new feature, you can execute only the functional test suite to test that the program works as intended. Or maybe create a performance test. Whenever it comes to dependencies upgrade or efficiency improvement, you could execute the performance test suite to assure that the efficiency matches the specs. The test suite can be simplified as the photo shown below.

Test Suites

OK now, I’m going to use the package “suite” of our trusty package “testify”.

The suite package provides you high flexibility about how and when you execute your code in a test suite. You are in control of every step of code execution. For instance, you could execute some setup code before/after the suite execution. Or even execute some code before/after each test in a suite. The test suite execution process is shown in the below diagram.

Test suite execution process

Example

I’m going to create a calculator test suite just to test add and subtract functions. There are examples of how to execute codes before/after the suite and tests execution. The example code is shown below.

calculator test suite

Here’s the result of the execution. (I added some arrows and dashes to make it easier to read.)

>>> From SetupSuite
-- From SetupTest
From TestAddOne
-- From TearDownTest
-- From SetupTest
From TestSubtractOne
-- From TearDownTest
>>> From TearDownSuite
PASS

And that’s how you create a test suite. Thank you for reading and remember guys, whenever you developing a program, always write tests!

If you haven’t read Part1 and Part2 of this series, please don’t forget to check them out.

References

--

--