|
Boost Users : |
Subject: [Boost-users] [Test] Unit test for const suggestion.
From: MA (anlmat_at_[hidden])
Date: 2010-09-22 17:53:35
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
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net