2015-07-20 123 views
0

我需要测试类(比方说,这就是所谓的Caller)用这种方法:比较指针cointainers在googlemock

void Caller::callMe(map<string, string> argument); 

那类包含一个指向另一个类(比方说Executor),其中有这方法:

void Executor::addVector(vector< shared_ptr<AbstractClass> > aVector); 

我想测试的是,当被调用Caller::callMe(),它使用map<string>参数来创建ConcreteClass对象(AbstractClass接口的实现),创建一个vector< shared_ptr<ConcreteClass> >对象和通行证是Executor::addVector()

为此,我创建了一个MockExecutor如:

MOCK_METHOD1(addVector, void(vector<shared_ptr<AbstractClass> >)); 

,并把它传递给我的Caller实例。

Caller::callMe()方法从我正在通过的地图派生出vector< shared_ptr<ConcreteClass> >,即在调用Caller::callMe()之前,矢量的值是未知的。

这意味着,为了测试是否在载体中ConcreteClass项目与期望值相符,我不能只是做:

vector< shared_ptr<ConcreteClass> > expectedVector; 
for(size_t i = 0; i < expectedLength; ++i) 
{ /* initialise vector with expected values */ } 

EXPECT_CALL(*mockExecutor, addVector(expectedVector)); 

EXPECT_CALL(*mockExecutor, addVector(ElementsAre(..., ...)); 

因为shared_ptr项目会有所不同,我实际上需要比较指向的值by the shared_ptr items,也处理从AbstractClassConcreteClass的剧组。

我读过,有可能使用Pointee() [1]比较googlemock中指向的值,并且可以使用SafeMatcherCast() [2]进行类型转换,但是我有一些麻烦,工作。

如何在googlemock中编写这样的测试?或者,是否有可能使用自定义匹配器来实现这一点?

谢谢!

[1] https://code.google.com/p/googlemock/wiki/CookBook#Validating_the_Value_Pointed_to_by_a_Pointer_Argument

[2] https://code.google.com/p/googlemock/wiki/V1_7_CookBook#Casting_Matchers

+0

看,如果这篇文章有助于解决您的问题:http://stackoverflow.com/questions/7616475/can-google-mock-a-method-with-a-smart-pointer-return-type/11548191# 11548191 –

+0

谢谢,但这似乎不能解决我的问题,或者至少我看不出如何将其应用于我的情况。其实我意识到我需要更具体,所以我编辑了我的问题添加更多细节。 – sampei

回答

0

有可能是几种不同的方法来做到这一点,但在我脑海中使用自定义匹配的第一件事。假设上述具体类看起来是这样的:

class ConcreteClass : public AbstractClass { 
public: 
    unsigned value; 
}; 

你可以写一个自定义的匹配,其负责的向下转换为你:

MATCHER_P(DownCastClassHasValue, value, "") { 
    return reinterpret_cast<const ConcreteClass*>(&arg)->value == value; 
} 

这会正是如此使用:

EXPECT_CALL(*mockExecutor, addVector(AllOf(
     Contains(Pointee(DownCastClassHasValue(1))), 
     Contains(Pointee(DownCastClassHasValue(2)))))); 

& c。期望并不完美,但我认为它会做你想做的。

+0

谢谢,那个工作:) – sampei