接口和模板在C ++中的依赖注入 [英] Interfaces vs Templates for dependency injection in C++

查看:141
本文介绍了接口和模板在C ++中的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了能够单元测试我的C ++代码我通常传递的类的测试一个或severel对象的构造函数可以是生产代码或假/ mock对象(我们称之为这些注入对象)。我已经这样做了


  1. 创建一个接口,生产代码类和fake / mock类继承。 >
  2. 让类测试一个模板类,它将注入对象的类型作为模板参数,并将注入对象的实例作为构造函数的参数。



    1. 一些随机的想法:




      • 直到我们有概念

      • 不能始终为旧代码创建接口

      • 只有文档和参数命名才会提示要提供的测试类
      • 基本上只能创建接口以执行依赖注入

      • 以相同的方式:测试下的类的模板仅用于启用依赖注入



      你的想法是什么?有没有其他解决方案这个问题?

      解决方案

      我认为接口选项更好,但不必创建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

      1. Creating an interface that both the "production code" class and the fake/mock class inherits.
      2. 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.

      Some random thoughts:

      • 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

      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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆