假设我正在测试一个声明一些内部变量的方法(在堆栈上)。变量通过引用传递给一个对象(方法setupFoo()
)以使用正确的值填充它,然后通过引用传递给另一个对象(方法useFoo()
)来使用这些值。
如何编写EXPECT_CALL和匹配器以验证对模拟方法的两次调用是否都获得相同的引用?现在我只是使用_
忽略引用。
你可以这样做:
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))));