Const behavior test with googletest
I am using google test to write some unit tests for a container class with iterators. I would like to create a test that ensures mine is const_iterator
correct const
: namely, that I cannot assign it
MyContainer<MyType>::const_iterator cItr = MyContainerInstance.cbegin();
*cItr = MyType(); // this should fail.
Obviously this won't compile (IFF is correctly coded), but is there a way to use google test to leave some kind of check like this in the unit test? Or in some way without a Google test that doesn't require another library to be integrated?
source to share
This way it can be determined if an iterator is a constant iterator, but this is more complicated than I originally thought.
Keep in mind that you don't need an actual instance of your constant iterator, since all you do is type checking:
// Include <type_traits> somewhere
typedef MyContainer<MyType>::const_iterator it;
typedef std::iterator_traits<it>::pointer ptr;
typedef std::remove_pointer<ptr>::type iterator_type;
std::cout << std::boolalpha << std::is_const<iterator_type>::value;
// This'll print a 0 or 1 indicating if your iterator is const or not.
And then you can check in the usual way in gtest with:
EXPECT_TRUE(std::is_const<iterator_type>::value);
Free advice: I think it's best to let your compiler check this for you by simply writing a test that won't compile if it breaks const correctness.
You can check this with std::vector
:
typedef std::vector<int>::const_iterator c_it;
typedef std::iterator_traits<c_it>::pointer c_ptr;
typedef std::remove_pointer<c_ptr>::type c_iterator_type;
EXPECT_TRUE(std::is_const<c_iterator_type>::value);
typedef std::vector<int>::iterator it;
typedef std::iterator_traits<it>::pointer ptr;
typedef std::remove_pointer<ptr>::type iterator_type;
EXPECT_FALSE(std::is_const<iterator_type>::value);
This should compile and run.
source to share