我如何验证2种模拟方法以相同的参考调用



假设我正在测试一种声明某些内部变量(在堆栈上)的方法。该变量通过参考一个对象(方法setupFoo())传递,以用正确的值填充它,然后通过引用另一个对象(方法useFoo())传递以使用值。

如何编写我的Expect_calls和Matchers来验证两个对模拟方法的调用是否获得相同的参考?现在,我只使用_来忽略参考。

您可能会做类似:

的事情
const void* ref = nullptr;
EXPECT_CALL(mock, setupFoo(_)).WillOnce(Invoke([&](const auto& ptr) { ref = &ptr;}));
EXPECT_CALL(mock, useFoo(_)).WillOnce(Invoke([&](auto& ptr) { EXPECT_EQ(ref, &ptr);}));

另一个选项,使用Truly()调用:

template <class T>
struct SameReference {
    const T **ptr;
    SameReference(const T **pointer) : ptr(pointer){}
    bool operator()(const T &ref) const {
        if (*ptr == nullptr) *ptr = &ref;
        return *ptr == &ref;
    }
};
template <class T>  SameReference<T> sameReference(T *&ptr){return SameReference<T>(&ptr);}

...

const ErrorInfo *asThis = nullptr;
EXPECT_CALL(errorUtils, setupError(Truly(sameReference(asThis))));
EXPECT_CALL(responseCreator, createException(Truly(sameReference(asThis))));

最新更新