最近使用gtest进行单元测试,采用打桩的形式。关于gtest的详细说明就不多说了,网上的资料一大堆。主要讲解使用时的参数如何配置以及遇到的问题。下面的例子模拟是加、减、乘、除四则运算,前提是不知道加、减、乘、除四则运算是如何实现的。
编译命令自己根据实际情况进行搭建
#include <iostream>
#include <vector>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <string>
using namespace testing;
using namespace std;
//using ::testing::Return;
//using ::testing::ByRef;
class Operator //要测试的接口分别是add() sub()
{
public:
virtual int add(int x, int y) = 0;//加法
virtual int sub(int x, int y) = 0; //减法
virtual int multi(int x, int y) = 0; //乘法
virtual int divide(int x, int y) = 0; //除法
};
class MockOperator : public Operator {
public:
MOCK_METHOD2(add, int(int x, int y)); //2代表add()有2个参数
int Operation::Add(Operator *op, int a, int b) {
return op->add(a, b);
}
int Operation::Sub(Operator *op, int a, int b) {
return op->sub(a, b);
}
int Operation::Multi(Operator *op, int a, int b) {
return op->multi(a, b);
}
int Operation::Divide(Operator *op, int a, int b) {
return op->divide(a, b);
}
TEST(OperatorTest, add) {
MockOperator mock;
int t = 13;
EXPECT_CALL(mock, add(6, 7)).WillRepeatedly(Return(t));
Operation op;
EXPECT_EQ(13, op.Add(&mock, 6, 7)); //13 与 Add的结果进行比较
}
TEST(OperatorTest, sub) {
MockOperator mock;
int t = -1;
EXPECT_CALL(mock, sub(6, 7)).WillRepeatedly(Return(t)); //设定返回值是t
Operation op;
EXPECT_EQ(-1, op.Sub(&mock, 6, 7)); //-1 与 Sub的结果进行比较
}
TEST(OperatorTest, multi) {
MockOperator mockoperator;
int t = 18;
EXPECT_CALL(mockoperator, multi(2, 9)).WillRepeatedly(Return(t)); //设定返回值为t
Operation op;
EXPECT_EQ(18, op.Multi(&mockoperator, 2, 9)); //18 与 Multi的结果进行比较
}
TEST(OperatorTest, divide) {
MockOperator mock;
int t = 3;
EXPECT_CALL(mock, divide(15, 5)).WillRepeatedly(Return(t)); //设定返回值为t
Operation op;
EXPECT_EQ(3, op.Divide(&mock, 15, 5)); //3 与 Divide()的结果进行比较
}
int main(int argc, char **argv) {
std::cout << "start gtest" << endl;
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
结果如下: