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