Search code examples
c++visual-studiocode-organization

What is an effective way to organize C++ projects that are going to be unit tested?


I am wondering what would be an effective way to organize C++ projects and classes that are going to be unit tested. I have read many SO posts related to unit test but couldn't find practical examples.

Here are some ways I have collected:

Method A

  • Project A: Application (.exe) project that "include" the classes from Project C
  • Project B: Unit test (.exe) project that "include" the classes from Project C
  • Project C: Static library (.lib) project that keeps all classes that Project A uses

Method B

  • Project A: Application (.exe) project with all classes inside itself.
  • Project B: Unit test (.exe) project that "links" to classes in Project A

Method C (from Miguel)

  • only one project, with three configurations:
    • Debug: builds your Application .exe in debug mode.
    • Release: builds your Application .exe in release mode.
    • Test: builds the unit test framework, replaces your app's main() with the unit testing main()

Which is the more appropriate way? Do you have any other suggestions?


Solution

  • I have previously used the first method quite well. Have most of your code in a static library project, have the main executable project just contain the main function, and have your tests and the test main function in a third project. The two executable projects will link to the static library and reuse the code.

    The main benefits in doing it this way are:

    • The code that is being tested is the exact same build as is used in your application.
    • You can test both the debug and release configurations to ensure that both work as expected. (You can extrapolate debug and release for any configurations that you might require.)
    • Build time is minimised since the same built library is used in both executable projects.
    • Can have the build system build both the test and main executable at the same time, and also run the test executable after building.