c++ - 使用 googletest 测试 const 行为

标签 c++ unit-testing googletest

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

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

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

最佳答案

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

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

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

这应该可以编译通过。

关于c++ - 使用 googletest 测试 const 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29829810/

相关文章:

c++ - 如何链接 VS Code 问题匹配器的目录

c++ - 从派生**转换为基础**

php - TypeError: class::functionName() 的返回值必须是/Interface 的实例,返回 null

c++ - 如何使用 vsinstr/vsperfmon 获得真正的代码覆盖率

c++ - 如何让 Eclipse 控制台显示与终端中相同的 GoogleTests 输出?

c++ - Google 测试和 std::vector 范围异常

c++ - 在为嵌套类定义超出范围的友元时,我真的必须打破封装吗?

visual-studio-2008 - 当我添加 NUnit 后,TeamCity 就停止工作了

unit-testing - 这种依赖注入(inject)的设计容易理解吗?

c++ - 使用插件更改 C++ 应用程序中的默认行为