如何使用gmock匹配C ++元组中的一个元素?
例如,让我们尝试从std::string
中提取std::tuple<std::string, int>
。
我知道我可以写一个这样的自定义匹配器:
MATCHER_P(match0thOfTuple, expected, "") { return (std::get<0>(arg) == expected); }
但是,由于我找到Pair(m1, m2)
的{{1}}匹配器,我预计也会为std::pair
找到类似的内容。
Gmock有std::tuple
用于选择元组参数的子集。当只使用1个参数时,它仍然需要一个元组匹配器。以下尝试似乎没有编译:
Args<N1, N2, ..., Nk>(m)
让我的clang给出一个像这样的编译错误:
struct {
MOCK_METHOD1(mockedFunction, void(std::tuple<std::string, int>&));
} mock;
EXPECT_CALL(mock, mockedFunction(testing::Args<0>(testing::Eq(expectedStringValue))));
是否有.../gtest/googlemock/include/gmock/gmock-matchers.h:204:60: error: invalid operands to binary expression ('const std::__1::tuple<std::__1::basic_string<char> >' and 'const std::__1::basic_string<char>')
bool operator()(const A& a, const B& b) const { return a == b; }
...
的gmock解决方案类似于std::tuple
的gmock解决方案,它使用gmock std::pair
匹配器?
答案 0 :(得分:0)
testing::Args
用于将函数参数打包到元组 - 与你想要实现的完全相反。
我的建议 - 在你的情况下 - 在Mock课程中解压缩,见:
struct mock
{
void mockedFunction(std::tuple<std::string, int>& tt)
{
mockedFunctionUnpacked(std::get<0>(tt), std::get<1>(tt));
}
MOCK_METHOD2(mockedFunctionUnpacked, void(std::string&, int&));
};
然后:
EXPECT_CALL(mock, mockedFunctionUnpacked(expectedStringValue, ::testing::_));
不幸的是,目前的gmock匹配器都不适用于std :: tuple参数。
如果您想了解C ++模板 - 您可以尝试这一点(不完整 - 只是想知道如何实现元组匹配的一般功能):
// Needed to use ::testing::Property - no other way to access one
// tuple element as "member function"
template <typename Tuple>
struct TupleView
{
public:
TupleView(Tuple const& tuple) : tuple(tuple) {}
template <std::size_t I>
const typename std::tuple_element<I, Tuple>::type& get() const
{
return std::get<I>(tuple);
}
private:
Tuple const& tuple;
};
// matcher for TupleView as defined above
template <typename Tuple, typename ...M, std::size_t ...I>
auto matchTupleView(M ...m, std::index_sequence<I...>)
{
namespace tst = ::testing;
using TV = TupleView<Tuple>;
return tst::AllOf(tst::Property(&TV::template get<I>, m)...);
}
// Matcher to Tuple - big disadvantage - requires to provide tuple type:
template <typename Tuple, typename ...M>
auto matchTupleElements(M ...m)
{
auto mtv = matchTupleView<Tuple, M...>(m..., std::make_index_sequence<sizeof...(M)>{});
return ::testing::MatcherCast<TupleView<Tuple>>(mtv);
}
然后像这样使用:
EXPECT_CALL(mock, mockedFunction(matchTupleElements<std::tuple<std::string, int>>(expectedStringValue, ::testing::_)));