2 ms·
A unit test is something that calls the code you wrote, and makes sure that the responses are what they should be. It's often (though not always) written using
by AnimalMuppet 10y ago
A unit test is something that calls the code you wrote, and makes sure that the responses are what they should be. It's often (though not always) written using a testing framework, like jUnit or CxxTest. These frameworks handle some of the tedium of writing the tests, but not all of it - testing is tedious to do, and there's not much way around it.
What parts should be tested? Everything that can be conveniently tested, and some distance past that. The goal is "every externally visible behavior of a class"; that is, everything that matters to a caller. For example, let's suppose I have a "sorted container" class. I'd want to test that it returns stuff in sorted order, maybe with two or three items, and with lots (hundreds or thousands). I'd want to test that it handled duplicates correctly. I'd want to test that it worked correctly with only one item, and with zero. I would not want to test whether it was internally implemented with a vector - that's not something that the caller cares about. So if the sorted container is changed from a vector to a tree, the unit tests should run unchanged.
Just last week, I was breaking apart a singleton into three related singletons. "Related" means that they each need a reference (or pointer) to at least some of the others. Turns out I coded a recursive constructor loop. A unit test pointed that out to me.
I've seen unit tests catch race conditions. Catch that I was calling a pure virtual method in a base class destructor. Plus of course all a whole bunch of the usual regular bugs.