模拟对象 C++ [英] Mock object c++

查看:58
本文介绍了模拟对象 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关 TDD 的内容,并想知道是否可以在不使用像 easyMock 或诸如此类的额外测试库的情况下编写任何模拟对象.

I was reading about TDD and wondering is it possible to write any mock object without using extra test library like easyMock or sth like that.

例如我有代码:

class Person
{
  int age;
  int add ( int x) { return this.age + x }
}

如何编写模拟对象来测试上面的代码?

How to write mock object to test above code ?

推荐答案

您不会使用该类的模拟来测试这样的类.您测试接口.事实上,您的代码看起来像是测试其他一些代码的模拟对象.

You don't test a classes like that with a mock of that class. You test interfaces. In fact, your code looks like it could be a mock object to test some other code.

// defined in code that is being tested
class Person {
    virtual int add(int) = 0;
}
void foo(const Person& bar) {
    // use person somehow
}

要测试上述接口,您可以创建一个模拟对象.该对象没有实际实现可能具有的要求.例如,虽然实际实现可能需要数据库连接,但模拟对象不需要.

To test the above interface, you can create a mock object. This object does not have the requirements that a real implementation might have. For example while a real implementation might require a database connection, the mock object does not.

class Mock: public Person {
    int add(int x) {
        // do something less complex than real implementation would
        return x;
    }
}

Mock test;
foo(test);

如果您想测试一个模板函数,则不需要使用继承.

Using inheritance is not necessary if you want to test say, a template function.

template<class T>
void foo(T bar) {
    // Code that uses T.add()
}

要像这样测试接口,您可以像这样定义模拟对象

To test interface like this, you can define mock object like this

class Mock {
    int add(int x) {
        // do something less complex than real implementation would
        return x;
    }
}

这篇关于模拟对象 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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