接口和模板在C ++中的依赖注入 [英] Interfaces vs Templates for dependency injection in C++
问题描述
- 创建一个接口,生产代码类和fake / mock类继承。 >
- 让类测试一个模板类,它将注入对象的类型作为模板参数,并将注入对象的实例作为构造函数的参数。
- 直到我们有概念
- 不能始终为旧代码创建接口
- 基本上只能创建接口以执行依赖注入
- 以相同的方式:测试下的类的模板仅用于启用依赖注入
- Creating an interface that both the "production code" class and the fake/mock class inherits.
- Making the class under test a template class that takes the types of the injection objects as template parameters, and instances of the injection objects as parameters to the constructor.
- Until we have concepts (C++0x), only documentation and parameter naming will hint what to provide the class under test (when using templates).
- It is not always possible to create interfaces for legacy code
- The interface is basically only created to be able to do dependency injection
- In the same way: templating the class under test is done only to enable dependency injection
一些随机的想法:
只有文档和参数命名才会提示要提供的测试类
你的想法是什么?有没有其他解决方案这个问题?
我认为接口选项更好,但不必创建common base类只是用于测试。您可以从生产类继承您的模拟类,并覆盖必要的方法。你必须使这些方法是虚拟的,但是这是工具,如 mockpp 工作,他们也允许自动化这个处理一点。
To be able to unit test my C++ code I usually pass the constructor of the class under test one or severel objects that can be either "production code" or fake/mock objects (let's call these injection objects). I have done this either by
Some random thoughts:
What are your thoughts? Are there other solutions to this problem?
I think interface option is better, but one doesn't have to create common base class just for test. You can inherit your mock class from production class and override necessary methods. You'll have to make the methods virtual though, but that's how tools like mockpp work and they also allow automate this process a little bit.
这篇关于接口和模板在C ++中的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!