使用 googletest 测试 const 行为

Test for const behavior with googletest

我正在使用 google 测试为带有迭代器的容器 class 编写一些单元测试。我想创建一个测试来确保我的 const_iterator 是正确的 const:也就是说,我不能分配给它

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

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

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

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

// 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);

这应该可以编译通过。