Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Patterns for making c++ code easy to test

Should you design your code to make testing easier? And if so how to design c++ code so that it is easy to test.

  • How do you apply dependency-injection in c++?
  • Should I implement the classes using a pure interface class as the base in order to simplify the creation of fake test objects?
    • That would force me into making a lot of virtual methods. Will that affect performance?
  • What else should I think about when designing for testability in c++?
like image 372
Joakim Karlsson Avatar asked Nov 05 '09 14:11

Joakim Karlsson


3 Answers

Don't design too much up from the start, then write a test, then make it pass, but not more than that. Keep your functions very short. Look what you've done and refactor it. If you're going to write a comment, better put the code in question to a separate function with a good name.

And don't spend too much time thinking of patterns, that's a lot of science and little outcome, just write a test first and keep your code simple, then, surprisingly you don't need to write tests for it, you've done it already. And your code works.

like image 60
Dmitry Avatar answered Sep 20 '22 21:09

Dmitry


Should I implement the classes using a pure interface class as the base in order to simplify the creation of fake test objects?

  • That would force me into making a lot of virtual methods. Will that affect performance?

A workaround I often use is to templatize the class instead of hiding it behind an interface. Then I can pass test/mock objects as template parameters when testing, and the real objects otherwise. That way, the performance hit of virtual functions is avoided.

Edit
Ok, a simple example:

With OOP and interfaces, you might write a function such as this:

void Foo(IBar& someBar) { ... }

This function takes a parameter which implements the IBar interface, and does something with it. If you want to pass in a dummy mock implementation, you simply write a mock object which inherits from IBar and pass that to Foo. Simple and straightforward.

But you can achieve the same thing with templates:

template <typename BarType>
void Foo(BarType& someBar) { ... }

... and that's it. The body of Foo can be pretty much unchanged. As long as the type passed to the function exposes all the members we need, it'll work, without having to formally inherit from an interface class, and without the overhead of virtual functions and runtime polymorphism.

like image 32
jalf Avatar answered Sep 21 '22 21:09

jalf


Maximum cohesion and minimum coupling.

This will make your life easier with testing.

like image 21
bua Avatar answered Sep 20 '22 21:09

bua