简体   繁体   中英

Create gmock tests for template specialization methods

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);
}
}

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.

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM