gpt4 book ai didi

c++ - googlemock 框架不适用于虚拟继承

转载 作者:太空宇宙 更新时间:2023-11-04 12:57:34 26 4
gpt4 key购买 nike

看起来我在尝试模拟接口(interface)时无法使用虚拟继承。我需要使用虚拟继承,因为我的代码依赖于第三方库。第 3 方库使用虚拟继承通过父级从一个子级转换为另一个。我们需要能够根据 3rd 方库的期望进行模拟,但事实并非如此。

注意:IA、IB、IC 和 ID 是第 3 方库

class IA
{
};

class IB :virtual public IA
{
};

class IC :virtual public IB
{
public:
int getValue(){}
};

class ID : virtual public IA
{
public:
void type(){};
};

class MockD :
public ID
//virtual public ID; fails all of my tests that depends on ID
{
public:
MOCK_METHOD0(type, void())
};

class MockC :
//virtual public IC, virtual public MockD{}; //throws an exception for accessing pD->type()
// public IC, virtual public MockD{}; //throws an exception for accessing pD->type()
//virtual public IC, public MockD{}; //throws an exception for accessing pC->getValue()
// public IC, public MockD{}; //throws an exception for accessing pD->type()
{
MOCK_METHOD0(getValue, void());

};
//throws an exception for accessing pD->type()


IA
_______
(v)/ \(v)
IB ID
(v)| |
IC MockD
| |
(v)\ /(v)
MockC


IA
_______
(v)/ \(v)
IB ID
(v)| |
IC MockD
| |
\ /(v)
MockC


IA
_______
(v)/ \(v)
IB ID
(v)| |
IC MockD
| |
\ /
MockC

//throws an exception for accessing pC->getValue()

IA
_______
(v)/ \(v)
IB ID
(v)| |
IC MockD
| |
(v)\ /
MockC
IA

待测代码

ID* pD = dynamic_cast<ID*>(pC);
pD->type();
pC->getValue();

//在测试中

MockC* mockC = new MockC();
EXPECT_CALL(mockC, type());
EXPECT_CALL(mockC, getValue());

最佳答案

您只需要从 ID 派生的 Mock 对象并模拟其所有功能。然后忘记 MockC 并以您需要的方式定义 MockD:

class MockD : public ID 
{
public:
MOCK_METHOD0(type, void());
MOCK_METHOD0(getValue, int());
};

并以这种方式设置您的测试期望:

MockD mockD;
EXPECT_CALL(mockD, type());
EXPECT_CALL(mockD, getValue()).WillOnce(Return(0)); //not sure you want zero - use return value that you needs

然后 - 假设这是 void codeUnderTest(IC& c) - 您要测试的代码 - 只需将 mockD 传递给此代码:

codeUnderTest(mockD);

如果您出于某些其他原因同时需要 MockDMockC - 然后使用模板定义来实现此目标:

template <typename Interface>
class MockCT : public Interface
{
public:
MOCK_METHOD0(getValue, int());
};
using MockC = MockCT<IC>;

template <typename Interface>
class MockDT : public MockCT<Interface>
{
public:
MOCK_METHOD0(type, void());
};
using MockD = MockDT<ID>;

关于c++ - googlemock 框架不适用于虚拟继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45873062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com