【发布时间】:2016-04-06 11:55:04
【问题描述】:
当我从 Google 研究 Gmock 时,我已经安装并构建了项目,到目前为止运行良好。但我对模拟函数有些担心。现在我有以下文件:
myGtest.h
#ifndef MYGTEST_H_
#define MYGTEST_H_
int test(int);
int function(int);
#endif /* MYGTEST_H_ */
src_code.cpp
#include <stdio.h>
#include "myGtest.h"
int test(int a) {
printf("NOT overridden!\n");
return a;
}
int function(int a){
int x = test(a);
if(x == 0)
return 99;
else
return 0;
}
myGtest_dummy.h
#ifndef MYGTEST_DUMMY_H_
#define MYGTEST_DUMMY_H_
#include "gmock/gmock.h"
#include "../myGtest/myGtest.h"
class myGtestMock
{
public:
myGtestMock(){};
~myGtestMock(){};
MOCK_METHOD1(test, int(int));
};
#endif /* MYGTEST_DUMMY_H_ */
test_program.cpp
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "src/myGtest/myGtest.h"
#include "src/dummy/myGtest_dummy.h"
using testing::_;
using testing::Return;
using testing::InSequence;
using ::testing::AtLeast;
extern int function(int a);
extern int test(int a);
class BTest:public testing::Test{
public:
myGtestMock mock_test;
int __wrap_test(int a);
};
int BTest::__wrap_test(int a){
printf("overridden!\n");
return a;
}
TEST_F(BTest, CallMockTest) {
EXPECT_CALL(mock_test, test(0))
.WillOnce(Invoke(this, &BTest::__wrap_test));
function(99);
}
int main(int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
你能帮我解释一下吗:如何模拟函数int test(int)?我希望一旦执行TEST_F(BTest, CallMockTest),程序就会调用function(99);。然后我的模拟函数int __wrap_test(int) 将被调用而不是int test(int)。
非常感谢您的回答。
【问题讨论】:
标签: c++ unit-testing testing googletest gmock