静态依赖注入和 GMock 委托
我们将首先将您的示例最小化为以下内容(以使后面的段落尽可能不嘈杂):
// a.h
#include <string>
// class to mock
class A {
static std::string get_id();
};
// b.h
#include <string>
#include "a.h"
// class that use A
struct B {
std::string foo() const {
return A::get_id();
}
};
虽然您不能更改A,但您可以在产品代码中将B 更改为静态注入 A,而您可以静态注入A 的模拟委托用于测试代码:
// b.h
#include <string>
#include "a.h"
namespace detail {
// The type template parameter is set to A by default,
// and should not need to override this default type
// in production code, but can be injected with
// mocked classes in test code.
template<typename AImpl = ::A>
struct BImpl {
std::string foo() const {
return A::get_id();
}
};
} // namespace detail
// Expose product-intent specialization.
using B = BImpl<>;
A 的模拟使用静态(非线程安全)方法来模拟对注入的静态类型的调用:
// a_mock.h
#include <memory>
#include <string>
#include "gmock/gmock.h"
class AMock {
// Mocked methods.
struct Mock {
MOCK_CONST_METHOD0(get_id,
std::string());
};
// Stubbed public API for static function of object under test:
// delegates stubbed calls to the mock.
static std::string get_id() {
if (const auto mock = mock_.lock()) {
mock->get_id();
}
else {
ADD_FAILURE()
<< "Invalid mock object! The test can no "
"longer be considered useful!";
}
}
// Public setter to specify the mock instance used in test (which in
// turn will be the instance that Google Test's EXPECTS and mocked
// calls is placed upon).
static void setMock(const std::shared_ptr<Mock>& mock) { mock_ = mock; }
private:
// Pointer to mock instance.
static std::weak_ptr<Mock> mock_;
};
最后可以在BImpl的测试中使用如下:
// b_test.cpp
#include "b.h" // object under test
#include "gmock/gmock.h"
#include "a_mock.h"
class BImplTest : public ::testing::Test {
public:
using BImplUnderTest = BImpl<AMock>;
BImplTest() : amock_(std::make_shared<AMock::Mock>()) {
AMock::setMock(amock_);
}
};
TEST_F(BImplTest, foo) {
// Setup mocked call(s).
EXPECT_CALL(amock_, foo()).WillOnce(::testing::Return( /*...*/ ));
// Call object under test.
BImplUnderTest b{};
b.foo();
}
进一步隐藏B实际上是类模板BImpl的特化这一事实
如果你开始大量使用这种模式(在不同的子例程上以滑动窗口的方式)并且想要避免单个大而臃肿的翻译单元,你可以移动 detail::B 类的成员函数的定义用于分隔标头的模板,例如 b-timpl.h(包括 b.h)和与 b.h 关联的源文件中,例如 b.cpp,包括 b-timpl.h 而不是 b.h,并为生产添加显式实例化定义意图detail::BImpl 专业化:
// b.cpp
template class ::detail::BImpl<>;
而在::detail::BImpl 的测试中,您包括b-timpl.h 而不是b.h,并为类模板的模拟注入专业化添加显式实例化定义:
// b_test.cpp
#include "b-timpl.h"
// ...
template class ::detail::BImpl<AMock>;
// ...
为什么? BImpl 类未参数化以允许其接口的用户静态注入不同的行为(对于用户意图,用户应该只看到 B),但允许在测试时注入模拟或存根类。