如何在EXPECT_CALL中使用ElementsAreArray匹配器

时间:2019-06-27 12:36:32

标签: c++ googletest googlemock

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_;

1 个答案:

答案 0 :(得分:2)

我认为无法使用ElementsAreArray(或任何其他硬币容器匹配器)来做到这一点

如果我正确地阅读了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;
}

但是,这需要传递一个有效的对象( braised-init-lists 不适用于模板):

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