嘲笑 C++具有依赖注入的类
假设您正在测试类 A
并且它有一个 依赖注入 B
具有 C
的依赖注入。
因此您模拟 B
但它唯一的构造函数需要注入 C
,所以你必须模拟C
也是如此,将模拟的 C
注入模拟的 B
中,然后再将其注入到 A
中?
如果您有 5 个连续受抚养人怎么办?
有哪些替代方案?
我使用 Google Mock,因此具体的答案也会有所帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
埃米尔的想法是正确的,你应该依赖接口而不是具体的类。所以在你的例子中,它会是这样的:
在你的测试中,你创建一个不依赖于任何类C的模拟B。然后你只用B测试接口。这样你就打破了A对C的依赖。创建一个模拟不依赖于 C 的 B 非常简单:
Emile has the right idea, you should depend on interfaces not concrete classes. So in your example it would be something like:
In your tests you create a mock B which does not rely on any class C. Then you are only testing the interface with B. In this way you break A's dependency on C. Creating a mock B that doesn't depend on C is pretty simple:
如果您更改设计,使类依赖于接口而不是具体类,那么您就可以摆脱构造函数问题。除了提高可测试性之外,它还可能提高可重用性和可维护性,但代价是更多的代码(接口)。
If you change the design so that the classes depend on interfaces instead of concrete classes, you get rid of the constructor problems. Besides improving testability, it may also improve reusability and maintainability, at the cost of more code (interfaces).
在这种情况下,您应该通过指针而不是通过引用注入,然后您可以传递 NULL 指针。假设您的对象确实是一个模拟对象而不是一个假对象,那么这将起作用,因此它对注入的对象没有真正的依赖性。
对于
boost::shared_ptr
你可以执行以下操作: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: