问题
I want to add GMOCK tests to verify if the container accesses the correct method.
For vector
it should access the second method, and for set
it should access the first method (because set
has set.find
).
This is my template specialization:
namespace tools{
struct low_priority {};
struct high_priority : low_priority {};
template<class TSource, class Ty>
auto exists_in(high_priority, const TSource &source, const Ty &item)
-> decltype(source->find(item) != source.end())
{
return source.find(item) != source.end();
}
template<class TSource, class Ty>
auto exists_in(low_priority, const TSource &source, const Ty &item)
{
return std::find(source.begin(), source.end(), item) != source.end();
}
template<class TSource, class Ty>
auto exists_in(const TSource &source, const Ty &item)
{
return exists_in(high_priority{}, source, item);
}
}
回答1:
You cannot use mock from free functions or template methods.
What you can do in that case is create a custom struct and check whether operator<
(for std::set::find
) or operator==
(for std::find
) is called.
Alternatively, you might create mock type for std::set
and check that find
method is called.
回答2:
I did this alternatively way, for a vector, but it does not work, how i properly check if that method is called?
struct Interface
{
virtual ~Interface() = default;
virtual bool exists_in(std::vector<int>, int) = 0;
};
struct Implementation : Interface
{
bool exists_in(std::vector<int> v, int i) override { tools::exists_in(v, i); }
};
class MockClass : public Interface {
public:
MOCK_METHOD(bool, exists_in, (std::vector<int>, int));
};
**ADDED NEW**
TYPED_TEST_SUITE_P(ExistsInTestMethod);
TYPED_TEST_P(ExistsInTestMethod, ExistsInMethod)
{
TypeParam Container = InitVectorContainer<TypeParam>();
MockClass mock;
EXPECT_CALL(mock, exists_in(Container, 5));
}
来源:https://stackoverflow.com/questions/65705945/create-gmock-tests-for-template-specialization-methods