用依赖注入模拟C ++类 [英] Mocking C++ classes with dependency injection
问题描述
说你正在测试课程 A
,它有一个依赖注入 B
,其依赖注入为 C
。
所以你嘲笑 B
,但它唯一的构造函数需要注入 C
,所以你必须模拟 C
,并将嘲笑的 C
注入嘲笑的 B
中,然后再注入它是 A
?
如果你有5个连续的关系怎么办?
有什么办法? p>
我使用 Google Mock ,因此具体的答案也将有所帮助。
在这种情况下,你应该注意指针而不是引用,那么你可以通过NULL指针。这将工作,假设你的对象确实是一个模拟而不是一个假的对象,因此它没有真正的依赖注入的对象。
对于 boost :: shared_ptr
可以执行以下操作:
boost :: shared_ptr< C> null_c_ptr;
MockB mock_b(null_c_ptr);
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?
What are the alternatives?
I use Google Mock, so a specific answer would help as well.
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.
For boost::shared_ptr
you could do the following:
boost::shared_ptr<C> null_c_ptr;
MockB mock_b(null_c_ptr);
这篇关于用依赖注入模拟C ++类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!