项目推荐CPP单元测试打桩
不管你是开发的老码农,还是新入职场菜鸟,只要你是项目里负责写代码的,都得多多少少写点单元测试代码。企业对质量也会有些要求,像单元测试的覆盖率达到100%这种要求。
其实单元测试达到60%左右可能效率上最高,发挥的作用最大。但硬性指标就是硬性指标,还是得想办法来满足指标要求。
推荐一项开源项目cpp-stub,专门为C++单元测试打桩而设计的,使用简单的API就能完成函数的替换,让你的覆盖率分分钟达到100%。项目介绍支持的操作系统 : windows,linux 支持的硬件平台 : x86,x86-64,arm64,arm32,mips64 支持的编译器 : msvc,gcc,clang 示例了各种获取函数的方法,像构造函数、虚函数、私有函数、模板函数、重载函数、仿函数、静态函数地址等基于gtest、catch2框架模板
项目地址:https://github.com/coolxv/cpp-stub
打桩概念:用新实现的函数替换被测代码中的函数,当运行时原先执行函数1,当函数1被函数2替换(即打桩)时,就会运行函数2。类成员函数例子#include #include "stub.h" using namespace std; class A{ int i; public: int foo(int a){ cout<<"I am A_foo"< #include "stub.h" #include "addr_pri.h" using namespace std; class A{ int a; int foo(int x){ cout<<"I am A_foo "<< a << endl; return 0; } static int b; static int bar(int x){ cout<<"I am A_bar "<< b << endl; return 0; } }; ACCESS_PRIVATE_FIELD(A, int, a); ACCESS_PRIVATE_FUN(A, int(int), foo); ACCESS_PRIVATE_STATIC_FIELD(A, int, b); ACCESS_PRIVATE_STATIC_FUN(A, int(int), bar); int foo_stub(void* obj, int x) { A* o= (A*)obj; cout<<"I am foo_stub"< #include "stub.h" using namespace std; template void * get_ctor_addr(bool start = true) { //the start vairable must be true, or the compiler will optimize out. if(start) goto Start; Call_Constructor: //This line of code will not be executed. //The purpose of the code is to allow the compiler to generate the assembly code that calls the constructor. T(); Start: //The address of the line of code T() obtained by assembly char * p = (char*)&&Call_Constructor;//https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html int offset = *(int *)(p + 8); void * ret = p + 12 + offset; return ret; } class A { public: A(){cout << "I am A_constructor" << endl;} }; class B { public: B(){cout << "I am B_constructor" << endl;} }; int main() { Stub stub; auto xa = get_ctor_addr(); auto xb = get_ctor_addr(); stub.set(xa, xb); A aa; return 0; }