[Test] Unit test for const suggestion.
Hi there! I have been having some trouble unit testing const variables/types in my code. The problem I had was basically: The compiler stops the compilation with an error if you try to change a const variable/type. Still you want to write a unit test that checks that the variable cannot be changed. So to check that the variable/type cannot be changed we can just check if the variable/type is const or not. By doing so we indirectly check that the variable/type cannot be changed. So the suggestion for the Boost.Test library is to create a BOOST_CHECK_IS_CONST that works something like the code below but with the BOOST_CHECK_EQUAL syntax: ------ #include <iostream> #include <boost/type_traits.hpp> template<typename T > bool isconst(T&, typename boost::enable_if<boost::is_const< T >, T >::type* = 0 ) { return true; } template< typename T > bool isconst(T&, typename boost::disable_if<boost::is_const< T >, T>::type* = 0 ) { return false; } int main() { const int const_int = 0; int plain_int = 0; std::cout << isconst(const_int) << std::endl; std::cout << isconst(plain_int) << std::endl; } ----- By doing this you can check for const in a unit test like this: BOOST_CHECK_EQUAL(isconst(const_int), true); But it would be nicer with a BOOST_CHECK_IS_CONST. Regards, anlmat
[Please do not mail me a copy of your followup] boost-users@lists.boost.org spake the secret code <i7dmr3$e9c$1@dough.gmane.org> thusly:
The compiler stops the compilation with an error if you try to change a const variable/type. Still you want to write a unit test that checks that the variable cannot be changed. [...]
IMO there is little value to be had by writing such a test, since as you state above you can't assign to a const quantity and still have the code compile. Test the behavior of your classes and leave the const'ness of members and variables up to the implementor of the class. -- "The Direct3D Graphics Pipeline" -- DirectX 9 draft available for download <http://legalizeadulthood.wordpress.com/the-direct3d-graphics-pipeline/> Legalize Adulthood! <http://legalizeadulthood.wordpress.com>
participants (2)
-
legalize+jeeves@mail.xmission.com
-
MA