EXPECT_CALL(*backendHttpResponseStatusLogger, LogValue(0, ElementsAreArray({ "ip1:p1", "pool1", "setting1", "1xx" }))).Times(1);
给我编译错误如下。什么是使用它的正确方法。
LogValue函数的签名为
void(int64_t, const string[])
/appgwtlib/googletest/googletest-release-1.8.0/googlemock/include/gmock/gmock-matchers.h: In instantiation of 'class testing::internal::ElementsAreMatcherImpl<const std::__cxx11::basic_string<char>*>':
/appgwtlib/googletest/googletest-release-1.8.0/googlemock/include/gmock/gmock-matchers.h:3532:23: required from 'testing::internal::ElementsAreArrayMatcher<T>::operator testing::Matcher<T>() const [with Container = const std::__cxx11::basic_string<char>*; T = const char*]'
NginxMetricHandlerTests.cpp:85:3: required from here
/appgwtlib/googletest/googletest-release-1.8.0/googlemock/include/gmock/gmock-matchers.h:3114:45: error: 'testing::internal::ElementsAreMatcherImpl<const std::__cxx11::basic_string<char>*>::StlContainer {aka const std::__cxx11::basic_string<char>*}' is not a class, struct, or union type
typedef typename StlContainer::value_type Element;
^
/appgwtlib/googletest/googletest-release-1.8.0/googlemock/include/gmock/gmock-matchers.h:3248:43: error: 'testing::internal::StlContainerView<const std::__cxx11::basic_string<char>*>::type {aka const std::__cxx11::basic_string<char>*}' is not a class, struct, or union type
::std::vector<Matcher<const Element&> > matchers_;
最佳答案
我认为不可能使用ElementsAreArray
(或任何其他cointainer匹配器)来做到这一点
如果我正确阅读documentation,我不是100%,但是看来C样式数组必须通过引用传递,或者必须与它的大小一起传递,以使匹配器起作用。
注意此错误:
error: 'testing::internal::ElementsAreMatcherImpl<const std::__cxx11::basic_string<char>*>::StlContainer {aka const std::__cxx11::basic_string<char>*}' is not a class, struct, or union type
GMock内部类的成员称为
StlContainer
,但它是std::string*
。除非您传递数组中的元素数量(否则,在处理C样式数组时您可能应该这样做),否则它将无法正常工作。
相反,您可以编写自己的匹配器,比较器将不安全地(不知道数组的实际大小)比较元素:
MATCHER_P(CStyleArrayEqual, arrayToCompare, "")
{
int i = 0;
for(const auto& elem: arrayToCompare)
{
//very, VERY unsafe! You don't know the length of arg!
//std::initializer_list doesn't have operator[], have to resort to other methods
if(arg[i] != elem)
return false;
++i;
}
return true;
}
但是,这需要传递一个有效的对象(带有括号的初始列表不适用于模板):
EXPECT_CALL(*backendHttpResponseStatusLogger, LogValue(0, CStyleArrayEqual(std::vector<std::string>{"1", "2"})));
为了避免显式命名类型,您可以预先声明变量:
auto arrayToMatch {"1", "2"}; //type is std::initializer_list<std::string>
EXPECT_CALL(*backendHttpResponseStatusLogger, LogValue(0, CStyleArrayEqual(arrayToMatch)));
See it online
关于c++ - 如何在EXPECT_CALL中使用ElementsAreArray匹配器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56791171/