【问题标题】:Mocking classes with template methods使用模板方法模拟类
【发布时间】:2020-04-29 11:40:20
【问题描述】:

是否有任何模式用于测试使用公共 api 中包含模板方法的类的类?我知道在动态多态模拟接口中是这样的解决方案:

struct Interface {
 virtual void foo() = 0; 
 virtual ~Interface() = default;
};

class TestedClass {
public:
  TestedClass(Interface& i) {}
  // ... rest of the class
};

struct IMock : public Interface {
 void foo() override {} 
};

void test() {
  IMock bar;
  TestedClass baz(bar);
}

但是我可以用下面的东西做什么?有没有一种惯用的方法来测试这个?

struct Interface {
 template<class T>
 void foo() {
   // do stuff depending on type
 }
};

class TestedClass {
public:
  TestedClass(Interface& i) {}
  // ... rest of the class
  // uses Interface foo with multiple types
};

【问题讨论】:

  • 你测试模板,或者一个类,或者任何你想测试的东西,看看结果,你的问题到底是什么,不清楚。

标签: c++ unit-testing c++11


【解决方案1】:

要允许模拟,在这种情况下,您需要

template &lt;typename InterfaceT&gt; class TestedClass;

所以您现在可以拥有TestedClass&lt;Interface&gt;(用于生产)和TestedClass&lt;MockInterface&gt;(用于测试)。

struct Interface {
 template<class T>
 void foo() {
   // do stuff depending on type
 }
};

template <typename InterfaceT>
class TestedClass {
public:
  TestedClass(InterfaceT& i) {}
  // ... rest of the class
  // uses Interface foo with multiple types
};

struct MockInterface {
 template<class T>
 void foo() {
   // do mock-stuff depending on type
 }
};

void test() {
  MockInterface bar;
  TestedClass baz(bar); // Or pre CTAD of C++17: TestedClass<MockInterface> baz(bar);
}

【讨论】:

  • 并不是我对这样的解决方案非常满意(模板错误太可怕了),但我想没有比这更好的了
猜你喜欢
  • 2022-07-27
  • 1970-01-01
  • 2016-04-12
  • 2015-07-12
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多