Writing C++ unit tests near function/class declarations -


When it comes to writing unit tests for functions or classes in C ++, then it is in separate source files from the original They start writing popular announcements and definitions (like math_test.cpp for math.hpp / math.cpp). I am surprised that writing them near the announcement will be better for the following reasons:

  • Users can see how to use a function or a class from its unit test
  • Developers can clearly tell whether the function or class has a unit test

For example, I wonder if I can put a unit test into a header file in the function declaration I can:

// plus.hpp int plus (int a, int b); UNITTEST {emphasis (plus (1, 2) == 3); }

While the source file is always the usual one:

  // plus cpp int plus (int a, int b) {a + b; }  

And when I define a specific macro (like ENABLE_UNITTEST), I hope the unit code is evaluated by the compiler and the test runner will be executed by executable.

My questions are:

  1. Is it good practice to write unit tests near such announcements?
  2. Is there an existing C ++ test framework that supports writing type of this type? (I think this will be the cause of a redefinition error when plus.hpp is included in many source files if the framework is not implemented properly)
  3. If 2 is the answer Is this possible to implement a test like this?

Such announcements?

No, it is not so. More unit test codes are not unusual than actual codes. Mixing two makes it harder for your system to maintain and make refactors.

The idea of ​​entering an entity test with the main code appeals to small code examples like you. In many instances, however, your unit's test code can easily quadruple your actual code quadruple, especially if you aim to high code coverage, the simplest size of the code added, with its in-code documentation, People will make it difficult to change your system.

In addition, some unit tests require maintaining the state during running (setup and general test outline deal with this) teardown functions of the deal with the placeholder for the state with payload codes Will be made even more complex.

Is there an existing C ++ test framework, which supports writing like this?

It is not what I know.

If 2 is the answer, is it possible to implement such a test framework? It is definitely possible - for example, you can run all kinds of tricks with preprocessor macros and conditional compiles to remove unit tests from your "payload" code. And compile them separately. I do not think it's desirable, though.


Comments

Popular posts from this blog

java - Can't add JTree to JPanel of a JInternalFrame -

javascript - data.match(var) not working it seems -

javascript - How can I pause a jQuery .each() loop, while waiting for user input? -