我是gmock测试的新手。我有Foo类,它有成员函数set()和start()。 Start()触发set()和类成员member1设置为1,member2设置为2.当我尝试在gmock中测试这个时,我看不到这些成员被设置。为什么以及如何解决这个问题?感谢。
test.h文件
#ifndef TEST_H_
#define TEST_H_
#include <gtest/gtest.h>
#include <gmock/gmock.h>
class Foo
{
public:
Foo();
virtual~Foo();
int member1;
int member2;
virtual void set();
virtual void start();
};
class MockFoo:public Foo
{
public:
MOCK_METHOD0(set, void());
};
#endif /* TEST_H_ */
simpleGmock.cpp文件
#include <stdio.h>
#include <stdlib.h>
#include "test.h"
using ::testing::AtLeast;
using ::testing::Return;
Foo::Foo(){};
Foo::~Foo(){};
void Foo::set()
{
member1=1;
member2=2;
}
void Foo::start()
{
this->set();
}
TEST(simplesuite, callmethods)
{
MockFoo mockfoo_obj;
EXPECT_CALL(mockfoo_obj, set())
.Times(AtLeast(1))
.WillOnce(::testing::Return());
mockfoo_obj.start();
ASSERT_EQ(mockfoo_obj.member1,1);
}
int main( int argc, char *argv[] ) {
::testing::InitGoogleMock( &argc, argv );
return RUN_ALL_TESTS( );
}
,结果如下:
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from simplesuite
[ RUN ] simplesuite.callmethods
simpleGmock.cpp:39: Failure
Expected: mockfoo_obj.member1
Which is: -528070912
To be equal to: 1
[ FAILED ] simplesuite.callmethods (0 ms)
[----------] 1 test from simplesuite (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] simplesuite.callmethods
1 FAILED TEST
答案 0 :(得分:0)
尝试删除.WillOnce(::testing::Return())
,因为它会导致Foo::set()
无法被调用,因为您正在模拟该函数。
您可能需要在EXPECT_CALL之后手动调用Foo :: set(),因为在模拟方法之后,不再调用被覆盖的函数。尝试添加.WillOnce( Invoke( this, &Foo::set ) )