使用依赖注入模拟 C++ 类 [英] Mocking C++ classes with dependency injection
问题描述
假设您正在测试类 A
,它有一个 依赖注入B
的 a> 具有 C
的依赖注入.
所以你模拟 B
但它拥有的唯一构造函数需要注入C
,所以你是否也必须模拟 C
并将模拟的 C
注入模拟的 B
并且只然后将其注入到 A
?
如果你有 5 个连续的依赖项怎么办?
Say you're testing class A
and it has a dependency injection of B
which has a dependency injection of C
.
So you mock B
but the only constructor it has requires an injection of C
, so do you have to mock C
as well and inject the mocked C
into the mocked B
and only then inject it to A
?
What if you have 5 consecutive dependancies?
有什么选择?
我使用 Google Mock,所以具体的答案也会有所帮助.
I use Google Mock, so a specific answer would help as well.
推荐答案
在这种情况下你应该通过指针而不是通过引用来注入,那么你可以传递一个 NULL 指针.假设您的对象确实是模拟对象而不是假对象,这将起作用,因此它对注入的对象没有真正的依赖关系.
In this case you should inject by pointer and not by reference, then you could pass a NULL pointer. This would work assuming you're object is indeed a mock and not a fake object, therefore it has no real dependency on the injected object.
对于 boost::shared_ptr
您可以执行以下操作:
For boost::shared_ptr
you could do the following:
boost::shared_ptr<C> null_c_ptr;
MockB mock_b(null_c_ptr);
这篇关于使用依赖注入模拟 C++ 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!