googlemock学习整理
1.例子
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)
注意:
析构函数 必须是虚函数
方法也得定义为纯虚函数
2.模版
EXPECT_CALL(mock_object, Method(argument-matchers))
.Times(cardinality)
.InSequence(sequences)
.After(expectations)
.WillOnce(action)
.WillRepeatedly(action);
- EXPECT_CALL声明一个调用期待,就是我们期待这个对象的这个方法按什么样的逻辑去执行
- mock_object是我们mock的对象,上例中就是TestUser的一个对象。
- Method是mock对象中的mock方法,它的参数可以通过argument-matchers规则去匹配
- Times表示这个方法可以被执行多少次。如果超过这个次数,则按默认值返回了。
- InSequence用于指定函数执行的顺序。它是通过同一序列中声明期待的顺序确定的。
- After方法用于指定某个方法只能在另一个方法之后执行。
- WillOnce表示执行一次方法时,将执行其参数action的方法。一般我们使用Return方法,用于指定一次调用的输出。
- WillRepeatedly表示一直调用一个方法时,将执行其参数action的方法。需要注意下它和WillOnce的区别,WillOnce是一次,WillRepeatedly是一直。