Go unit test setup and teardown
Go’s unit testing library provides support for simple unit test setup and teardown functions. This unfortunately lacks the ability to pass arguments (mocks) to setup/teardown functions. Luckily Go itself provides language features for custom setup and teardown functions. Consider the following contrived math library function that needs unit testing:
And a simple table driven sub unit test to cover all code paths:
An updated test case with setup/teardown functions per test case and setup/teardown functions per sub test.
To run test cases and see setup/teardown log messages type:
% go test -v
And observe the output:
To run a single subtest run:
% go test -run=TestAddition/add -v
You can checkout the source code from from GitHub:
% git clone https://github.com/kare/go-unit-test-setup-teardown/