首页 > 解决方案 > 如何在 gmock expect_call 中对结构参数进行部分匹配

问题描述

struct obj
{
  int a;
  string str;
  string str2;
  bool operator==(const obj& o) const
  {
     if(a == o.a && str == o.str && str2 == o.str2) return true;
     return false;
   } 
}

然后在类中的一个函数中,它使用结构对象作为输入参数:

bool functionNeedsToBeMocked(obj& input)
{
  //do something
}

现在我想做的是,

EXPECT_CALL(*mockedPointer, functionNeedsToBeMocked( /* if input.a == 1 && input.str == "test" && input.str2.contains("first")*/  )).Times(1).WillOnce(Return(true));

输入值为

inputFirst.a = 1;
inputFirst.str = "test";
inputFirst.str2 = "something first";

我希望 inputFirst 可以与我的 EXPECT_CALL 匹配。

我怎么能使用 EXPECT_CALL 匹配器来做到这一点?

我确实看到了

EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")),
                      NULL));

在 gmock 食谱上,但我不知道如何为结构参数执行 HasSubStr。

标签: c++googletestgooglemock

解决方案


您可以为结构实现自己的匹配器obj

当您键入:

EXPECT_CALL(*mockedPointer, functionNeedsToBeMocked(some_obj)).Times(1).WillOnce(Return(true));

然后 gmock 使用默认匹配器,Eq使用some_obj作为其预期参数和匹配器中的实际functionNeedsToBeMocked参数argEqmatcher 将默认调用bool operator==预期和实际对象:

EXPECT_CALL(*mockedPointer, functionNeedsToBeMocked(Eq(some_obj))).Times(1).WillOnce(Return(true));

但是,由于您不想使用bool operator==,您可以编写一个自定义匹配器(删除Times(1),因为它也是默认匹配器):

// arg is passed to the matcher implicitly
// arg is the actual argument that the function was called with
MATCHER_P3(CustomObjMatcher, a, str, str2, "") {
  return arg.a == a and arg.str == str and (arg.str2.find(str2) != std::string::npos); 
}
[...]
EXPECT_CALL(*mockedPointer, functionNeedsToBeMocked(CustomObjMatcher(1, "test", "first"))).WillOnce(Return(true));

有可能使用匹配Field器和内置匹配器来编写自定义匹配器,HasString但让我们“将其作为练习留给读者”:P


推荐阅读