使用 googletest 测试常量行为



我正在使用谷歌测试为带有迭代器的容器类编写一些单元测试。我想创建一个测试,以确保我的const_iterator正确const:即,我无法分配给它

MyContainer<MyType>::const_iterator cItr = MyContainerInstance.cbegin();
*cItr = MyType();    // this should fail.

显然这将无法编译(IFF 编码正确),但是有没有办法使用 google test 在单元测试中留下这样的检查?或者没有谷歌测试的某种方式不需要集成另一个库?

因此,可以检测迭代器是否是常量迭代器,但这比我最初想象的要棘手。

请记住,您

不需要常量迭代器的实际实例,因为您所做的只是类型检查:

// 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.

然后,您可以在gtest中以通常的方式检查:

EXPECT_TRUE(std::is_const<iterator_type>::value);

免费建议:我认为最好让你的编译器为你检查这一点,只编写一个测试,如果它违反了常量正确性,它将无法编译。

您可以使用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);

这应该既编译又传递。

最新更新