GoogleTest 使用指南 | 测试私有静态方法
GoogleTest 使用指南 | 测试私有静态方法
新建一个测试访问类,使用测试访问类作为友元。
即可将测试对象的私有静态方法,通过测试访问类的公共方法间接调用。
utility.h:
class Utility {
private:
static int PrivateStaticMethod(int x) {
return x * 2;
}
// 使用测试类作为友元
friend class UtilityTestAccess;
};
// 测试访问类
class UtilityTestAccess {
public:
static int CallPrivateMethod(int x) {
return Utility::PrivateStaticMethod(x);
}
};
test_utility.cpp:
#include "gtest/gtest.h"
#include "utility.h"
TEST(UtilityTest, PrivateStaticMethod) {
EXPECT_EQ(UtilityTestAccess::CallPrivateMethod(5), 10);
EXPECT_EQ(UtilityTestAccess::CallPrivateMethod(0), 0);
EXPECT_EQ(UtilityTestAccess::CallPrivateMethod(-1), -2);
}
测试输出:
"/Users/xiye/CppProjects/unit-test-example/out/build/Clang 17.0.0 arm64-apple-darwin24.6.0/test_utility"
➜ Clang 17.0.0 arm64-apple-darwin24.6.0 "/Users/xiye/CppProjects/unit-test-example/out/build/Clang 17.0.0 arm64-apple-darwin24.6.0/test_utility"
Running main() from /Users/xiye/CppProjects/unit-test-example/out/build/Clang 17.0.0 arm64-apple-darwin24.6.0/_deps/googletest-src/googletest/src/gtest_main.cc
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from UtilityTest
[ RUN ] UtilityTest.PrivateStaticMethod
[ OK ] UtilityTest.PrivateStaticMethod (0 ms)
[----------] 1 test from UtilityTest (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.
4837

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



