Alf P. Steinbach wrote:
OK, this displays my ignorance of what's out there (it's been a long
time since I developed for a living), and also my laziness not
googling. :-)
However.
I want to unit-test some library code I'm sort of extracting from some
old code I have.
The things that should work without error are easy to test, and it's
currently not so much code that I've considered a testing framework,
although the code size increases. I'm thinking that perhaps the
popular frameworks don't support my needs: there are cases where the
code /should/ assert at run time. And worse, there are cases where the
could should assert at compile time...
I used to use cppUnit (and still do for older projects) but now I use
gtest (http://code.google.com/p/googletest/). Compile time asserts are
beyond the scope of a unit testing framework; if it won't compile, there
isn't a unit to test!
How do you deal with this kind of testing, testing that things fail as
they should (at compile time and at run time)?
For run time asserts, I interpose whatever function the system's assert
macro calls (__assert on Solaris) and have __assert throw an exception
with the file, line and expression passed by assert.
A boiled down (no framework) example:
#include <iostream>
#include <exception>
#include <assert.h>
struct AssertionException : std::runtime_error
{
const char* expression;
const char* file;
int line;
AssertionException(const char* expression, const char* file, int line)
: std::runtime_error( expression ),
expression(expression), file(file), line(line) {}
};
void __assert(const char* expression, const char* file, int line)
{
throw AssertionException( expression, file, line );
}
void fut( const char* p )
{
assert( NULL != p );
}
int main()
{
try
{
fut( NULL );
std::cerr << "Oops" << std::endl;
}
catch( const AssertionException& e )
{
std::cerr << "Caught" << ": " << e.what() << std::endl;
}
}
liberally to document internal assumptions and invariants.
designed for this purpose. The primary disadvantage of using an