Google的开源C++单元测试框架Google Test,简称gtest。
建议直接参考: https://www.cnblogs.com/coderzh/archive/2009/04/06/1426755.html
#include<gtest/gtest.h> int Abs(int x) { return x > 0 ? x : -x; } TEST(IsAbsTest,HandlerTrueReturn) { ASSERT_TRUE(Abs(1) == 1) << "Abs(1)=1"; //ASSERT_TRUE期待结果是true,operator<<输出一些自定义的信息 ASSERT_TRUE(Abs(-1) == 1) << "Abs(-1)=1"; ASSERT_FALSE(Abs(-2) == -2); //期待结果是false ASSERT_EQ(Abs(1),Abs(-1)); ASSERT_NE(Abs(-1),0); ASSERT_LT(Abs(-1),2); ASSERT_GT(Abs(-1),0); ASSERT_LE(Abs(-1),2); ASSERT_GE(Abs(-1),0); }
功能一:断言 简单理解为调节判断作用
TEST(TestSuiteName,TestCaseName) { EXPECT_*(**);// 失败时,案例继续往下执行。 ASSERT_*(**);// 失败时,直接在当前函数中返回,当前函数中ASSERT_*后面的语句将不会执行。 } int _tmain(int argc, _TCHAR* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
功能二:事件机制
1)全局的,所有案例执行前后。 class FooEnvironment : public testing::Environment { public: virtual void SetUp() // SetUp()方法在所有案例执行前执行 { std::cout << "Foo FooEnvironment SetUP" << std::endl; } virtual void TearDown() //TearDown()方法在所有案例执行后执行 { std::cout << "Foo FooEnvironment TearDown" << std::endl; } }; int _tmain(int argc, _TCHAR* argv[]) { testing::AddGlobalTestEnvironment(new FooEnvironment); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
2)TestSuite级别的,在某一批案例中第一个案例前,最后一个案例执行后。 class FooTest : public testing::Test { protected: static void SetUpTestCase() { //在第一个TestCase之前执行 shared_resource_ = new ; } static void TearDownTestCase() { //最后一个TestCase之后执行 delete shared_resource_; shared_resource_ = NULL; } // Some expensive resource shared by all tests. static T* shared_resource_; }; TEST_F(FooTest, Test1) //第一个TestCase { // you can refer to shared_resource here } TEST_F(FooTest, Test2) //第二个TestCase { // you can refer to shared_resource here }
3)TestCase事件是挂在每个案例执行前后的,实现方式和上面的几乎一样,不过需要实现的是SetUp方法和TearDown方法: class FooCalcTest:public testing::Test { protected: virtual void SetUp() //在每个TestCase之前执行 { m_foo.Init(); } virtual void TearDown() { m_foo.Finalize(); //在每个TestCase之后执行 } FooCalc m_foo; }; TEST_F(FooCalcTest, HandleNoneZeroInput) { EXPECT_EQ(4, m_foo.Calc(12, 16)); } TEST_F(FooCalcTest, HandleNoneZeroInput_Error) { EXPECT_EQ(5, m_foo.Calc(12, 16)); }
功能三:参数化测试
TEST(IsPrimeTest, HandleTrueReturn) { EXPECT_TRUE(IsPrime(3)); EXPECT_TRUE(IsPrime(5)); EXPECT_TRUE(IsPrime(11)); EXPECT_TRUE(IsPrime(23)); EXPECT_TRUE(IsPrime(17)); } 改成: TEST_P(IsPrimeParamTest, HandleTrueReturn) { int n = GetParam(); EXPECT_TRUE(IsPrime(n)); } INSTANTIATE_TEST_CASE_P(TrueReturn, IsPrimeParamTest, testing::Values(3, 5, 11, 23, 17));
功能四:死亡测试和运行参数 ...
ASSERT_DEATH(statement, regex`); ASSERT_EXIT(statement, predicate, regex`); int _tmain(int argc, _TCHAR* argv[]) { testing::GTEST_FLAG(output) = "xml:"; testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }