如何模拟依赖项的成员变量? [英] How to mock a member variable of dependency?
问题描述
我有一个班级和成员:
class A
{
B obj;
public:
int f(int i){return obj.g(i);}
}
此处 B obj
是一个依赖项,需要从文件中运行时创建.在类A的单元测试中,我希望使用类型为 int(int)
的函数 g
来模拟 B obj
.
Here B obj
is a dependency that requires run-time creation from a file. In my unit test for class A, I wish to mock B obj
, with a function g
typed int(int)
.
如何编写测试代码以模拟 B obj
,然后测试 A :: f
.
How can I write my test code, to mock B obj
, and then test A::f
.
非常感谢.
推荐答案
您需要使用依赖注入来实现此目的.为此,让类 B
从接口继承,并让类 A
持有指向该接口的指针:
You need to use dependency injection to achieve this. To this end, have class B
inherit from an interface, and have class A
hold a pointer to that interface:
class IB
{
public:
virtual void g(int i) = 0;
};
class B : public IB
{
public:
void g(int i) {
// this is your real implementation
}
};
此外,要在类 A
中启用依赖项注入,请添加适当的构造函数或setter方法:
Also, to enable dependency injection in class A
, add appropriate constructor or setter method:
class A
{
private:
IB *obj;
public:
A() : obj(nullptr) {}
// You don't need both the constructor and setter, one is enough
A(IB *pB) : obj(pB) {}
// void setB(IB *pB) { obj = pB; }
int f(int i) { return obj->g(i); }
};
现在,在生产代码中,您将创建一个 B
类的对象,并将其传递给 A
类的对象(假设我们正在使用构造函数进行注入):
Now, in your production code you create an object of class B
and pass it to class A
object (assuming that we are using the constructor for injection):
B b;
A a(&b);
在测试阶段,您创建一个模拟类 BMock
并将该类的对象传递给类 A
对象:
During testing phase, you create a mock class BMock
and pass an object of that class to class A
object:
class BMock : public IB
{
public:
MOCK_METHOD1(g, int(int));
};
TEST(ATests, TestCase1)
{
BMock bmock;
A a(&bmock);
// Now you can set expectations on mock object, for example that g will
// return 100 when it receives 50 as argument
EXPECT_CALL(bmock, g(50)).WillOnce(Return(100));
// Now act by calling A::f, which will in turn call g from mock object,
// and assert on function return value
ASSERT_EQ(a.f(50), 100);
}
这篇关于如何模拟依赖项的成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!