Eug*_*acu 5 c++ googletest googlemock
如何使用 gmock 匹配 C++ 元组中的一个元素?
例如,让我们尝试std::string从 中提取std::tuple<std::string, int>。
我知道我可以编写一个像这样的自定义匹配器:
MATCHER_P(match0thOfTuple, expected, "") { return (std::get<0>(arg) == expected); }
Run Code Online (Sandbox Code Playgroud)
但既然我找到了Pair(m1, m2)的匹配器std::pair,我期望也能找到类似的东西std::tuple。
Gmock 用于Args<N1, N2, ..., Nk>(m)选择元组参数的子集。当仅使用 1 个参数时,它仍然需要一个元组匹配器。以下尝试似乎无法编译:
struct {
MOCK_METHOD1(mockedFunction, void(std::tuple<std::string, int>&));
} mock;
EXPECT_CALL(mock, mockedFunction(testing::Args<0>(testing::Eq(expectedStringValue))));
Run Code Online (Sandbox Code Playgroud)
并使我的 clang 给出如下编译错误:
.../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; }
...
Run Code Online (Sandbox Code Playgroud)
是否有std::tuple一种类似于std::pair使用 gmockPair匹配器的 gmock 解决方案?
testing::Args用于将函数参数打包到元组中 - 与您想要实现的目标完全相反。
我的建议 - 对于你的情况 - 在模拟类中解压,请参阅:
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&));
};
Run Code Online (Sandbox Code Playgroud)
然后:
EXPECT_CALL(mock, mockedFunctionUnpacked(expectedStringValue, ::testing::_));
Run Code Online (Sandbox Code Playgroud)
不幸的是,当前的 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);
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用:
EXPECT_CALL(mock, mockedFunction(matchTupleElements<std::tuple<std::string, int>>(expectedStringValue, ::testing::_)));
Run Code Online (Sandbox Code Playgroud)