简体   繁体   English

Visual C ++类测试

[英]Visual C++ class testing

Is there any way to easily test C++ classes in java way. 有没有办法以java方式轻松测试C ++类。

In java you can add static function main and run it directly from IDE 在java中,您可以添加静态函数main并直接从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++ ? 是否可以在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) 当然你可以创建另一个项目,但这是一个糟糕的解决方案(你可以创建项目,然后将其添加到解决方案或运行另一个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) 另一种方法是修改main()函数,或CWinApp :: InitInstance(),但如果更改文件Foo.h,VS将重建项目中的所有文件,具体取决于它(我们只想测试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 我创建的最好的方法是创建另一个项目(控制台),添加Foo.h和Foo.cpp,将公共静态函数run()添加到我的类Foo并从控制台项目中的main()函数运行它,就像这样

//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) 通过这种方式我可以单独测试我的类Foo(无需重新编译大项目)

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 . 我使用Boost测试库编写的测试代码,它与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. 因此,只要测试失败,我甚至无法构建主项目。

The workaround I use is to use a #define to decide what mode the app is in. 我使用的解决方法是使用#define来决定应用程序的模式。

I usually have a def.h file, which would have 我通常有一个def.h文件,它会有

#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. 如果此测试代码也需要在多个文件中进行更改,那么您所要做的就是在这些源文件中包含def.h。

Hope this helps 希望这可以帮助

Use the Boost Test Library . 使用Boost测试库 If your application has a GUI, its a littlebit difficult to integrate, but once it works, its quite simple and straightforward to write tests. 如果你的应用程序有一个GUI,它很难集成,但一旦它工作,它编写测试非常简单和直接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM