前言
第一章中已经编译出自带的sample例子,在build/googletest目录下可以看到sample的各种例子的可执行程序。
Google Test 附带了10个单元测试用例,难度由浅及深。
sample2主要演示了如何测试类。
源码学习
- sample2由三个部分组成:sample2.h , sample2.cpp , sample2UnitTest.cpp (作者对原始文档进行了命名调整,以便更好的进行说明)
- sample2.cpp对成员函数CloneCString()、Set()进行了具体的实现
#include "sample2.h"
#include <string.h>
// Clones a 0-terminated C string, allocating memory using new.
const char* MyString::CloneCString(const char* a_c_string) {
if (a_c_string == nullptr) return nullptr;
const size_t len = strlen(a_c_string);
char* const clone = new char[len + 1];
memcpy(clone, a_c_string, len + 1);
return clone;
}
// Sets the 0-terminated C string this MyString object
// represents.
void MyString::Set(const char* a_c_string) {
// Makes sure this works when c_string == c_string_
const char* const temp = MyString::CloneCString(a_c_string);
delete[] c_string_;
c_string_ = temp;
}
}
- sample2.h中用到了 构造函数、拷贝构造函数、析构函数,并定义了成员函数
#ifndef GOOGLETEST_SAMPLES_SAMPLE2_H_
#define GOOGLETEST_SAMPLES_SAMPLE2_H_
#include <string.h>

本文解析了GoogleTest自带的sample2单元测试案例,详细介绍了sample2的源码实现,包括MyString类的构造、拷贝构造、析构及成员函数的实现,并通过四个测试用例验证了其正确性。
最低0.47元/天 解锁文章
1150

被折叠的 条评论
为什么被折叠?



