文章目录
- 1.简介
- 2.用法
1.简介
示例#4教你如何同时使用googletest和’ googletest.h ’
2.用法
CMakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
project(hello_gtest VERSION 0.1.0)
add_executable(${PROJECT_NAME} sample.cc man.cc)
target_link_libraries(${PROJECT_NAME} gtest gmock pthread)
sample.h
// A sample program demonstrating using Google C++ testing framework.
#ifndef GOOGLETEST_SAMPLES_SAMPLE4_H_
#define GOOGLETEST_SAMPLES_SAMPLE4_H_
// A simple monotonic counter.
class Counter
{
private:
int counter_;
public:
// Creates a counter that starts at 0.
Counter() : counter_(0) {}
// Returns the current counter value, and increments it.
int Increment();
// Returns the current counter value, and decrements it.
int Decrement();
// Prints the current counter value to STDOUT.
void Print() const;
};
#endif // GOOGLETEST_SAMPLES_SAMPLE4_H_
sample.cc
#include "sample.h"
#include <stdio.h>
// Returns the current counter value, and increments it.
int Counter::Increment() { return counter_++; }
// Returns the current counter value, and decrements it.
// counter can not be less than 0, return 0 in this case
int Counter::Decrement()
{
if (counter_ == 0)
{
return counter_;
}
else
{
return counter_--;
}
}
// Prints the current counter value to STDOUT.
void Counter::Print() const { printf("%d", counter_); }
sample_unittest.cc
#include "sample.h"
#include "gtest/gtest.h"
namespace
{
// Tests the Increment() method.
TEST(Counter, Increment)
{
Counter c;
// Test that counter 0 returns 0
EXPECT_EQ(0, c.Decrement());
// EXPECT_EQ() evaluates its arguments exactly once, so they
// can have side effects.
EXPECT_EQ(0, c.Increment());
EXPECT_EQ(1, c.Increment());
EXPECT_EQ(2, c.Increment());
EXPECT_EQ(3, c.Decrement());
}
} // namespace
man.cc
#include <gtest/gtest.h>
#include <gmock/gmock.h>
int main(int argc, char *argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
- ref:gtest sample