PDA

View Full Version : QTestLib - Testing Exceptions



Dashboard
24th July 2010, 00:26
Hi,

I'm in the process of migrating a bunch of tests from UnitTest++ to QTestLib. I've gotten almost everything working aside from one thing - testing exceptions.

For example, using UnitTest++, I can verify the following function throws an exception using the CHECK_THROW macro.



int foo(int i)
{
if (i < 0)
throw std::invalid_argument("Invalid value for i");

// Do something
return i * 2;
}

...

// Ensure exception is thrown when negative value of i is passed
CHECK_THROW(foo(-1), std::invalid_argument);

// Ensure valid data works
CHECK(foo(0) == 0);
CHECK(foo(1) == 2);



Is there a suitable equivalent in QTestLib?

Thanks for any help.

ChrisW67
24th July 2010, 04:35
Could you do something like:


try {
foo(-1);
QFAIL("Exception not thrown");
}
catch (...) {
}

or

bool exceptionSeen = false;
try {
foo(-1);
}
catch (std::invalid_argument&) {
exceptionSeen = true;
}
QCOMPARE(exceptionSeen, true);

Dashboard
25th July 2010, 02:07
Thanks for the reply. I was hoping there might be an existing macro/feature I had overlooked, but I guess not.

I ended up creating a macro using a hybrid of the CHECK_THROW and QVERIFY macros:



#define QVERIFY_THROW(expression, ExpectedExceptionType) \
do \
{ \
bool caught_ = false; \
try { expression; } \
catch (ExpectedExceptionType const&) { caught_ = true; } \
catch (...) {} \
if (!QTest::qVerify(caught_, #expression ", " #ExpectedExceptionType, "", __FILE__, __LINE__))\
return; \
} while(0)

...

QVERIFY_THROW(foo(-1), std::invalid_argument);



Pretty much the same as your 2nd suggestion. Seems to work fine.