painter.h(启动客户端 会调用service penDown)
#pragma once
#include "turtle.h"
class Painter{
Brush* turtle;
public:
Painter(Brush* turtle) : turtle(turtle) {}
bool DrawCircle(int,int,int);
};
Painter.cpp
#include "../include/painter.h"
bool Painter::DrawCircle(int, int, int) {
turtle->PenDown();
return true;
}
服务类:
Brush.h
#pragma once
class Brush {
public:
virtual ~Brush() {}
virtual void PenUp() = 0;
virtual void PenDown() = 0;
virtual void ForWord(int distance) = 0;
virtual void Turn(int degrees) = 0;
virtual void GoTo(int x,int y) = 0;
virtual int GetX() const = 0;
virtual int GetY() const = 0;
};
测试类:
#include "mock_brush.h"
#include "painter.h"
#include "gtest/gtest.h"
using ::testing::AtLeast;
TEST(PainterTest, CanDrawSomething) {
MockBrush turtle;
EXPECT_CALL(turtle, PenDown())
.Times(AtLeast(1));
Painter painter(&turtle);
EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
}
Test_main.cpp
#include "gtest/gtest.h"
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
cmake文件:
cmake_minimum_required(VERSION 3.10)
project(conan-google-mock)
if (EXISTS ${CMAKE_BINARY_DIR}/conan_paths.cmake)
include(${CMAKE_BINARY_DIR}/conan_paths.cmake)
endif ()
set(CMAKE_CXX_STANDARD 11)
set(INCLUDE_SOURCE
include/mock_brush.h
include/painter.h
include/brush.h)
set(TEST_SOURCE
test/main.cpp
test/mock_brush_test.cc)
set(SRC_SOURCE src/Painter.cpp)
include_directories(include) # 头文件搜索路径
#引入第三方库
find_package(GTEST REQUIRED)
add_executable(mock_example ${INCLUDE_SOURCE} ${TEST_SOURCE} ${SRC_SOURCE})
target_link_libraries(mock_example GTest::GTest)
注意:
析构函数 必须是虚函数
方法也得定义为纯虚函数
EXPECT_CALL(mock_object, Method(argument-matchers))
.Times(cardinality)
.InSequence(sequences)
.After(expectations)
.WillOnce(action)
.WillRepeatedly(action);