gtest使用例子
最近使用gtest進(jìn)行單元測(cè)試,采用打樁的形式。關(guān)于gtest的詳細(xì)說明就不多說了,網(wǎng)上的資料一大堆。主要講解使用時(shí)的參數(shù)如何配置以及遇到的問題。下面的例子模擬是加、減、乘、除四則運(yùn)算,前提是不知道加、減、乘、除四則運(yùn)算是如何實(shí)現(xiàn)的。
編譯命令自己根據(jù)實(shí)際情況進(jìn)行搭建
#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 ? //要測(cè)試的接口分別是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個(gè)參數(shù)
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的結(jié)果進(jìn)行比較
}
TEST(OperatorTest, sub) {
?? ?MockOperator mock;
?? ?int t = -1;
?? ?EXPECT_CALL(mock, sub(6, 7)).WillRepeatedly(Return(t)); ?//設(shè)定返回值是t
?? ?Operation op;
?? ?EXPECT_EQ(-1, op.Sub(&mock, 6, 7)); ?//-1 與 Sub的結(jié)果進(jìn)行比較
}
TEST(OperatorTest, multi) {
?? ?MockOperator mockoperator;
?? ?int t = 18;
?? ?EXPECT_CALL(mockoperator, multi(2, 9)).WillRepeatedly(Return(t)); //設(shè)定返回值為t
?? ?Operation op;
?? ?EXPECT_EQ(18, op.Multi(&mockoperator, 2, 9)); ?//18 與 Multi的結(jié)果進(jìn)行比較
}
TEST(OperatorTest, divide) {
?? ?MockOperator mock;
?? ?int t = 3;
?? ?EXPECT_CALL(mock, divide(15, 5)).WillRepeatedly(Return(t)); //設(shè)定返回值為t
?? ?Operation op;
?? ?EXPECT_EQ(3, op.Divide(&mock, 15, 5)); ?//3 與 Divide()的結(jié)果進(jìn)行比較
}
int main(int argc, char **argv) {
?? ?std::cout << "start gtest" << endl;
?? ?::testing::InitGoogleTest(&argc, argv);
?? ?return RUN_ALL_TESTS();
}
?
結(jié)果如下:
總結(jié)
- 上一篇: GJB438C相比438B在文档种类上的
- 下一篇: 算法第四版课后习题答案 西安电子科技大学