public函数如何单元测试
类的public
函数在面向对象编程中是最常见亦是最常规的函数,但是其单元测试的展开跟普通函数并无二致(注:这里指的是没有其他对象依赖的情况,有依赖的场景请参考本系列的有依赖对象的场景文章),下面来看看具体如何实施。
1.首先构建测试套件,定义一个继承自testing::Test
的类
class modelTest : public testing::Test {
protected:
};
2.同样需要复写SetUp/TearDown
两个函数
class modelTest : public testing::Test {
protected:
**void SetUp() override {**
**}**
**void TearDown() override {**
**}**
};
3.定义想要测试单元测试需要用到的数据,并在SetUp
进行初始化,在TearDown
中进行清理或析构。
class modelTest : public testing::Test {
protected:
void SetUp() override {
**pm = new model;**
}
void TearDown() override {
**if (pm) {**
**delete pm;**
**pm = NULL;**
**}**
}
**model* pm;**
};
4.通过TEST_F
宏定义想要测试的类的public
函数的测试用例
TEST_F(modelTest, IsPrimeNegative) {
// This test belongs to the IsPrimeTest test case.
EXPECT_FALSE(pm->IsPrime(-1));
EXPECT_FALSE(pm->IsPrime(-2));
EXPECT_FALSE(pm->IsPrime(INT_MIN));
}
// Tests some trivial cases.
TEST_F(modelTest, IsPrimeTrivial) {
EXPECT_FALSE(pm->IsPrime(0));
EXPECT_FALSE(pm->IsPrime(1));
EXPECT_TRUE(pm->IsPrime(2));
EXPECT_TRUE(pm->IsPrime(3));
}
// Tests positive input.
TEST_F(modelTest, IsPrimePositive) {
EXPECT_FALSE(pm->IsPrime(4));
EXPECT_TRUE(pm->IsPrime(5));
EXPECT_FALSE(pm->IsPrime(6));
EXPECT_TRUE(pm->IsPrime(23));
}
对应的demo
源码,请点击 PublicFuc.
也可扫码关注博主同名公众号”不解之榬“,回复 ”public“ 获取