Skip to content

Instantly share code, notes, and snippets.

@toliuweijing
Last active December 15, 2015 00:39
Show Gist options
  • Save toliuweijing/5174734 to your computer and use it in GitHub Desktop.
Save toliuweijing/5174734 to your computer and use it in GitHub Desktop.
C++: Lightweight Unitest Framework
I have been looking for unitest frameworks and have tried some of them,
such as the one in Boost. They all look a little bit heavyweight and
take times to learn. So I decided to write one for my own use. After
all, what I write will fit what I need.
What I expect on a unitest framework depends on the way I use it.
Basically, I apply unitest on functions. Everytime I add a new function,
I write a corresponding unitest. Pure functions are easy to test. All
we need is to feed an input and verify the output. Functions that
work by side effects are tricky to test. Especially when it is a member
function and the state of that object is protected by private identifiers.
Nevertheless, a unitest case should be easy to plug-in/off and well-organized.
Here is it.
// This is a AutoFunctor.hpp file.
template<class T>
class AutoFunctor
{
public:
AutoFunctor(){}
virtual ~AutoFunctor()
{
std::count << typeid(trigger_).name() << “ is passed\n”;
}
private:
static T trigger_;
};
template<class T>
T AutoFunctor::trigger_;
// This is a AutoBlock.hpp file.
#define AUTOBLOCK(name) \
struct name::AutoFunctor<name> \
{ \
Name()
#define END_AUTOBLOCK }};
I didn’t like writing tests before. It took lots of work to organize.
It needed to be inserted into the Main and that was messy. I do think
tests are helpful though. It is a good timing to write tests right
after adding a new feature. Rigorous softwares are built on good designs
and testers.
There are cons on Test-driven development(TDD). Because it is the
same person who writes both the code and test, some blind spots
are not likely to be aware of.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment