【发布时间】:2015-06-05 17:01:33
【问题描述】:
我有以下设置:
class MockObject : public Parent
{
public:
MOCK_CONST_METHOD0( GetSecondMockedObject, const Parent&() );
MOCK_CONST_METHOD0( SomethingReturnsBool, const bool() );
};
我有
MockObject mockParentObj;
MockObject mockChildObj;
// I create the following expectation on mockChildObj
EXPECT_CALL( mockChildObj, SomethingReturnsBool() ).WillRepeatedly( Return( true ) );
// I create the following expectation on mockParentObj
EXPECT_CALL( mockParentObject, GetSecondMockedObject() ).WillRepeatedly( ReturnRef( mockChildObj ) );
// I am going to use the parent mock object somewhere
realProductionObject.SomeRealFunction( mockParentObject );
// Definition of SomeRealFunction is part of the production code
SomeRealFunction( Parent& pObject )
{
// Method #1
// This should call the parent mock object which should return the child
// mock object. Then on that object I call SomethingReturnsBool()
// and the value of "val" should be true.
const Parent& childObject = pObject.GetSecondMockedObject().
bool val = childObject.SomethingReturnsBool();
// Method #2
// This also throws an error
// bool val = pObject.GetSecondMockedObject().SomethingReturnsBool();
}
但是,当我执行代码时(与此代码有点不同,它编译时没有问题)我得到以下异常,它是由调用 SomethingReturnsBool() 引起的:
First-chance exception at 0x023CC193 in MyTest.exe: 0xC0000005: Access violation reading location 0xCCCCCCE8.
Critical error detected c0000374
我怀疑从调用 GetSecondMockObject() 返回的子模拟对象引用无效。我不知道还能如何通过它?我尝试使用:
ReturnPointee( &... ) 而不是 ReturnRef( ... ) 但这也没有用。
如果有任何建议,我将不胜感激!
【问题讨论】:
-
尝试通过引用
SomeRealFunction而不是值来传递mockParentObject。 -
感谢@RA 的回复。但是,这似乎并不能解决问题。
-
另外,您需要确保
SomeRealFunction中的childObject是const Parent&类型,而不是Parent。 -
我刚刚用我尝试过的东西更新了这个问题。
-
您上面的代码仍然没有显示
SomeRealFunction通过引用接收Parent。如果这不能解决问题,那么问题一定出在其他地方——否则我无法重现您的问题。
标签: c++ unit-testing googletest googlemock gmock