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

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

问题描述

为了能够对我的 C++ 代码进行单元测试,我通常会向被测类的构造函数传递一个或多个对象,这些对象可以是生产代码"或假/模拟对象(我们称之为注入对象).我已经这样做了

To be able to unit test my C++ code I usually pass the constructor of the class under test one or several objects that can be either "production code" or fake/mock objects (let's call these injection objects). I have done this either by

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

一些随意的想法:

  • 在我们有了概念 (C++0x) 之前,只有文档和参数命名会暗示要为被测类提供什么(使用模板时).
  • 并非总是可以为遗留代码创建接口
  • 接口基本上只是为了能够进行依赖注入而创建的
  • 以同样的方式:对被测类进行模板化只是为了启用依赖注入

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

What are your thoughts? Are there other solutions to this problem?

推荐答案

我认为接口选项更好,但不必为了测试而创建通用基类.您可以从生产类继承您的模拟类并覆盖必要的方法.不过,您必须使方法虚拟化,但这就是 mockpp 之类的工具的工作方式,它们还允许自动执行此操作稍微处理一下.

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天全站免登陆