Mock implementations in C++

爱⌒轻易说出口 提交于 2019-12-05 06:19:45

Just as I would not hand-author mock objects in Java, I would also not hand-author them in C++. Mock objects are not just stubbed out classes, but are test tools that perform automated checks like making sure certain methods are called, or that they are called in order, etc. I would take a look at the various mock object frameworks for C++ out there. googlemock looks interesting, but there are others.

Regarding how to abstract out the concept of controlling Audio resources from the implementation, I definitely favor using a C++ "interface" (pure virtual base class) with a generic name (e.g. Audio) and an implementation class named for what makes it special (e.g. OpenALAudio). I suggest you not embed the word "interface" or "I" into your class names. Embedding type or programmatic concepts into names has been falling out of vogue for many years (and can force widespread renaming when you, for example, elevate an "interface" to a full-fledged "class").

Developing to interfaces is an object-oriented concept and thus appropriate for C++. Some of the most important books on design specifically targeting C++ are all about programming to interfaces (which in C++ terms means programming using pure virtual base classes). For example, Design Patterns and Large Scale C++ Software Design.

"But I've hardly ever seen such interface-heavy designs in C++", for your information, I advise you just take a brief look at the microsoft COM way of doing. This technology, based on C++, is all about interface-heavy design.

Design by interface is a good way of programming. If you are used to it, continue this way.

If you find yourself limited with names, it is a good practice to use namespaces. And for an interface name, it is common to call them ISomething, so just call it IAudio.

I'd say that depends a lot on the specific situation and required complexity of the mock. I assume ideally you would use the original, but want to avoid that because of complex dependencies. Then it might be worth copy pasting the header and commenting everything out and re-enabling mock functionality as needed as you go on with the development of your testing code.

I must admit I have no practical experience with this, but it seems to me that the less intrusive you can be in your original code the better.

Did you consider using a mock framework, like Hippo Mocks?

From the wiki:

class Foo {
private:
    IBar *bar;
public:
    Foo(IBar *bar);
    int a(); //calls IBar::c
};

class IBar {
public:
    virtual ~IBar() {}
    virtual void b() = 0;
    virtual int c(std::string) = 0;
};

void TestAFunctionInFoo() {
    MockRepository mocks;
    IBar *barMock = mocks.InterfaceMock<IBar>();
    Foo *newFoo = new Foo(barMock);
    mocks.ExpectCall(barMock, IBar::c).With("hello").Return(42);
    newFoo->a();
    delete newFoo;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!