C ++ how can I reorganize this?

I have the code below in my test code in many places:

// // Make a function call while expecting an exception should be thrown // bool exceptionThrown = false; try { expectNotEqual(someData, anotherData, methodName); } catch(std::logic_error&) { exceptionThrown = true; } if(!exceptionThrown) throw std::logic_error(methodName+"exception not thrown"); 

It would be nice (more understandable, concise) if I could encapsulate it all and do something like:

  exceptionShouldBeThrown(expectNotEqual(someData, anotherData, methodName)); 

I don't want to use a macro ... does anyone know how I can achieve a single line above using C ++?

+4
source share
2 answers

I know you're not talking about macros, but why? They exist to generate code:

 #define SHOULD_THROW(x, name) \ { \ bool didThrow = false; \ try \ { \ x; \ } \ catch(...) { didThrow = true; } \ \ if (!didThrow) \ throw std::logic_error(name " did not throw."); \ } SHOULD_THROW(expectNotEqual(someData, anotherData), "expectNotEqual") 

If you really don't want to use macros, you need to get the functor to call:

 template <typename Func> void should_throw(Func pFunc, const std::string& pName) { bool didThrow = false; try { pFunc(); } catch (...) { didThrow = true; } if (!didThrow) throw std::logic_error(pName + " did not throw."); } 

Boost Bind helps here:

 should_throw(boost::bind(expectNotEqual, someData, anotherData), "expectNotEqual"); 

Of course, everything the functor does works, like lambda, etc. But if Boost is available, just use their test library :

 #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(test) { BOOST_CHECK_THROW(expectNotEqual(someData, anotherData) , std::logic_error); } 
+11
source

Exceptions for exceptional. That is, what you do not expect at runtime, for example, due to a memory error. You do not want to use an exception to test ordinary things at runtime. Just expect NotEqual to return true / false on success:

 if (expectNotEqual(someData, anotherData, methodName)) { //handle success } else { //handle failure (which would include someData==anotherData) } 
+2
source

Source: https://habr.com/ru/post/1304285/


All Articles