mardi 28 octobre 2014

Writing C++ unit tests near function/class declarations


Vote count:

0




When it comes to writing unit tests for functions or classes in C++, it seems popular writing them in separate source files from the original declarations and definitions (e.g. math_test.cpp for math.hpp/math.cpp). I wonder if writing them near the definitions might 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 a function or a class has a unit test or not


For example, I wonder I can put a unit test to a function declaration in a header file like this:



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


while the source file is as usual:



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


and only when I define a specific macro (e.g. ENABLE_UNITTEST) I expect the UNITTEST code to be evaluated by the compiler and executed by the test runner executable.


My questions are:



  1. Is it a good practice to write unit tests near the declarations like this?

  2. Is there any existing C++ testing framework that supports writing tests like this? (I think it will cause a redefinition error when plus.hpp is included in multiple source files if the framework is not properly implemented)

  3. If the answer for 2. is NO, is it possible to implement a testing framework like this?



asked 59 secs ago







Writing C++ unit tests near function/class declarations

Aucun commentaire:

Enregistrer un commentaire