简体   繁体   English

为模板专业化方法创建 gmock 测试

[英]Create gmock tests for template specialization methods

I want to add GMOCK tests to verify if the container accesses the correct method.我想添加 GMOCK 测试来验证容器是否访问了正确的方法。 For vector it should access the second method, and for set it should access the first method (because set has set.find ).对于vector它应该访问第二种方法,对于set它应该访问第一种方法(因为setset.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.在这种情况下,您可以做的是创建一个自定义结构并检查是否调用了operator< (对于std::set::find )或operator== (对于std::find )。

Alternatively, you might create mock type for std::set and check that find method is called.或者,您可以为std::set创建模拟类型并检查是否调用了find方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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