Please use CPPUNIT_ASSERT_EQUAL
, which takes an actual and expected value. This pretty much eliminates the need for formatting a string, as the actual and expected values will be printed in the failure message.
You could also copy the implementation of this macro and the function it invokes and add additional macros for other types of comparisons. Another idea I tried out would be to use operator overloading to capture the value out of an expression. This (ab)uses operator overloading to capture the expression, but it seems perhaps a bit too hackish. I have included it to give you an idea of what is possible, but would not recommend its use:
#include <iostream>
#include <sstream>
class ExpressionPrinter
{
public:
std::ostringstream result;
template<typename T> ExpressionPrinter& operator<<(const T& other)
{
result << other;
return *this;
}
template<typename T> ExpressionPrinter& operator<(const T& other)
{
result << " < ";
result << other;
return *this;
}
template<typename T> ExpressionPrinter& operator<=(const T& other)
{
result << " <= ";
result << other;
return *this;
}
template<typename T> ExpressionPrinter& operator>(const T& other)
{
result << " > ";
result << other;
return *this;
}
template<typename T> ExpressionPrinter& operator>=(const T& other)
{
result << " >= ";
result << other;
return *this;
}
template<typename T> ExpressionPrinter& operator==(const T& other)
{
result << " == ";
result << other;
return *this;
}
template<typename T> ExpressionPrinter& operator!=(const T& other)
{
result << " != ";
result << other;
return *this;
}
};
#define ASSERT(X) doAssert((X), (ExpressionPrinter() << X));
void doAssert(bool result, const ExpressionPrinter& message)
{
std::cout << "Result: " << result << ", Expression: " << message.result.str() << std::endl;
}
int main()
{
int i = 1, j = 2;
ASSERT(i < j);
return 0;
}