views:

272

answers:

3

Is there any way to easily test C++ classes in java way.

In java you can add static function main and run it directly from IDE

class Foo{
  ...
  public static void main(String args[])
  {
     System.out.println("Test class foo here");
  }
}

is it possible to do it in Visual C++ ?

Of course you can create another project, but it is bad solution(you sould create project, and then add it to solution or run another copy of Visual Studio)

Another way is to modify main() function, or CWinApp::InitInstance() but if you change file Foo.h, VS will rebuild all files from project, depending on it (we just want to test Foo.h & Foo.cpp)

The best way i founded is to create another project (console), add Foo.h and Foo.cpp to it, add public static function run() to my class Foo and run it from main() function in console project like this

//unitTester.cpp
include "Foo.h"
int main(...){
  Foo::run();
  return 0;
}

in such way i can test my class Foo separately (without recompiling the big project)

+4  A: 

When I feel like writing unit tests, I usually add another project that links in the test code + the classes being tested. The test code I write using the Boost Test Library, which nicely integrates with Visual Studio. I make my actual project dependent on the test project. The test project runs its executable as a post-build step. Therefore, as long as the tests fail, I cannot even build the main project.

Pukku
A: 

The workaround I use is to use a #define to decide what mode the app is in.

I usually have a def.h file, which would have

#define TEST

Then on the main file you write,

#ifdef TEST
    // test code
#else
    // main code
#endif

This condition check can be done in several places too if for testing you need to change things in several places. If this testing code needs changes in several files also, all you have to do is to include def.h in those source files.

Hope this helps

Sahasranaman MS
You can also create several project configurations: Release Main, Debug Main, Release Test, Debug Test. Then, the latter two would #define TEST in their project settings.
Pukku
That's cool. I should try that out. I believe its is possible in NetBeans also, because I use more of NetBeans than Visual Studio
Sahasranaman MS
A: 

Use the Boost Test Library. If your application has a GUI, its a littlebit difficult to integrate, but once it works, its quite simple and straightforward to write tests.

RED SOFT ADAIR