{"id":14955,"date":"2017-04-19T17:04:52","date_gmt":"2017-04-20T01:04:52","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/vcblog\/?p=14955"},"modified":"2020-02-18T10:34:33","modified_gmt":"2020-02-18T10:34:33","slug":"cpp-testing-in-visual-studio","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/cppblog\/cpp-testing-in-visual-studio\/","title":{"rendered":"C++ Unit Testing in Visual Studio"},"content":{"rendered":"<p>Testing is an increasingly important part of a software development workflow. In many cases, it is insufficient to test a program simply by running it and trying it out \u2013 as the scope of the project gets more involved, it becomes increasingly necessary to be able to test individual components of the code on a structured basis. If you\u2019re a C++ developer and are interested in unit testing, you\u2019ll want to be aware of Visual Studio\u2019s unit testing tools. This post goes through just that, and is part of a series aimed at new users to Visual Studio. \nThis blog post goes over the following concepts: <\/p>\n<ol>\n<li><a href=\"#Setup\">Setting Up Unit Testing<\/a><\/li>\n<li><a href=\"#Framework\">The Microsoft Native C++ Unit Test Framework<\/a><\/li>\n<li><a href=\"#TestExplorer\">Using the Test Explorer to Run Tests in the IDE<\/a><\/li>\n<li><a href=\"#CodeCoverage\">Determining Unit Test Code Coverage<\/a><\/li>\n<\/ol>\n<p><a name=\"Setup\"><\/a><\/p>\n<h4>Setting Up Unit Testing<\/h4>\n<p>The easiest and most organized way to set up unit tests is to create a separate project in Visual Studio for your tests. You can create as many test projects as you want in a solution and connect them to any number of other Visual Studio projects in that solution that contain the code you want to test. Assuming you already have some code that you want to test, simply follow these steps to get yourself set up: <\/p>\n<ol>\n<li>Right-click your solution and choose <strong><em>Add &gt; New &gt; Project<\/em><\/strong>. Click the <em>Visual C++ <\/em>category, and choose the <em>Test <\/em>sub-category. Select <em>Native Unit Test Project<\/em>, give the project a descriptive name, and then click <em>OK<\/em>. \n<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/Untitled2.png\" alt=\"Image New Project Wizard for Testing\" width=\"940\" height=\"653\" class=\"aligncenter size-full wp-image-14965\" \/><\/li>\n<li>Visual Studio will create a new project containing unit tests, with all dependencies to the native test framework already set up. The next thing to do is to add references to any projects that will be tested. Right-click the unit test project and choose <strong><em>Add &gt; Reference&#8230;<\/em><\/strong>\n<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/add-reference-unit-testing.png\" alt=\"Image Right-click Add &gt; Reference\" width=\"609\" height=\"682\" class=\"aligncenter size-full wp-image-14975\" \/><\/li>\n<li>Check any projects that you want to unit test from your test project, and then press <em>OK<\/em>.\n<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/add-reference-unit-testing-2.png\" alt=\"Add &gt; Reference\" width=\"785\" height=\"544\" class=\"aligncenter size-full wp-image-14976\" \/>\nYour unit testing project can now access your project(s) under test. You can now start writing tests, as long as you add #include statements for the headers you want to access. <\/li>\n<\/ol>\n<p><strong>NOTE:<\/strong> You will only be able to unit test public functions this way. To unit test private functions, you must write your unit tests in the same class as the code that is being tested. \n<a name=\"Framework\"><\/a><\/p>\n<h4>The Microsoft Native C++ Unit Test Framework<\/h4>\n<p>Visual Studio ships with a native C++ test framework that you can use to write your unit tests. The framework defines a series of macros to provide simplified syntax. <\/p>\n<p>If you followed the steps in the previous procedure, you should have a unit test project set up along with your main code. Open unittest1.cpp in your test project and look at the starting code provided: \n<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/default-tests.png\" alt=\"Image  Starting code provided when creating MSTest project. \" width=\"525\" height=\"350\" class=\"aligncenter size-full wp-image-14985\" \/>\nRight from the start, you\u2019ll notice that <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/hh694604.aspx\">dependencies <\/a>have already been set up to the test framework, so you can get to work writing your tests. Assuming you connected your test project to your project(s) under test via <em>Add &gt; Reference <\/em>earlier, you can simply add the #include statements for the header files of the code you want to test. <\/p>\n<p>Tests can be organized by using the <em>TEST_CLASS <\/em>and <em>TEST_METHOD <\/em>macros, which perform exactly the functions you\u2019d expect. A <em>TEST_CLASS <\/em>is a collection of related <em>TEST_METHODS<\/em>, and each <em>TEST_METHOD <\/em>contains a test. You can name your <em>TEST_CLASS <\/em>and <em>TEST_METHOD <\/em>anything you want in the brackets. It\u2019s a good idea to use descriptive names that make it easy to identify each test\/test group individually later. <\/p>\n<p>Let\u2019s try writing some basic asserts. At the <em>TODO <\/em>comment, write: \n<code>Assert::AreEqual(1, 1);<\/code><\/p>\n<p>This is a basic equality assert which compares two expressions. The first expression holds the expected value, the second holds the item you are testing. For the Assert to pass, both sides must evaluate to the same result. In this trivial example, the test will always pass. You can also test for values you don\u2019t want your expression to evaluate to, like this: \n<code>Assert::AreNotEqual(1, 2);<\/code><\/p>\n<p>Here, for the test to pass, the two expressions must not evaluate to the same result. While this kind of assert is less common, you may find it useful for verifying edge cases where you want to avoid a specific behavior from occurring. <\/p>\n<p>There are several other Assert functions that you can try. Simply type <em>Assert::<\/em> and let IntelliSense provide the full list to take a look. Quick Info tooltips appear for each Assert as you make a selection in the list, providing more context on their format and function. You can find a <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/hh694604.aspx\">full reference of features in the Microsoft C++ native framework <\/a>on MSDN. \n<a name=\"TestExplorer\"><\/a><\/p>\n<h4>Using the Test Explorer to Run Tests in the IDE<\/h4>\n<p>With Visual Studio, you\u2019re not restricted to running unit tests in the command line. The Text Explorer window in Visual Studio provides a simple interface to run, debug, and <a href=\"https:\/\/blogs.msdn.microsoft.com\/visualstudioalm\/2016\/10\/10\/parallel-test-execution\/\">parallelize<\/a> test execution. \n<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/test-explorer.png\" alt=\"Image Test Explorer window\" width=\"351\" height=\"462\" class=\"aligncenter size-full wp-image-14995\" \/>\nThis is a straightforward process. Once you connect your test project to your project(s) under test, add some #include directives in the file containing your unit tests to the code under test, and write some Asserts, you can simply run a full build. Test Explorer will then discover all your unit tests and populate itself with them. <\/p>\n<p><strong>NOTE:<\/strong> In .NET, a feature called <a href=\"https:\/\/devblogs.microsoft.com\/visualstudio\/2017\/03\/09\/live-unit-testing-in-visual-studio-2017-enterprise\/\">Live Unit Testing <\/a>is available. This feature is not currently supported in C++, so unit tests are discovered and executed only after you run builds. <\/p>\n<p>To run your unit tests, simply click the <strong>Run All <\/strong>link in the Test Explorer. This will build your project (though this process is skipped if the project is already up to date) then run all your tests. The Test Explorer indicates the passing tests with a checkmark and the failing tests with an X. A summary of execution results is provided at the bottom of the window. You can click on any failing unit test to see why it failed, including any exceptions that may have been thrown. Execution times for each unit test are also provided. For realistic test execution times, test in the Release solution configuration rather than Debug, which will provide faster runtimes which are more approximate to your shipped application. <\/p>\n<p>To be able to debug your code as you run your unit tests (so you can stop at breakpoints and so forth), simply use the <strong><em>Test &gt; Debug <\/em><\/strong>menu to run your tests.\n<a name=\"CodeCoverage\"><\/a><\/p>\n<h4>Determining Unit Test Code Coverage<\/h4>\n<p>If you are using Visual Studio Enterprise, you can run code coverage on your unit tests. Assuming you have unit tests already set up for your project, this is as simple as going to <strong><em>Test &gt; Analyze Code Coverage <\/em><\/strong>in the main Visual Studio menu at the top of the IDE. This opens the Code Coverage Results window which summarizes code coverage data for your tests. \n<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/code-coverage.png\" alt=\"Image Code Coverage Results window\" width=\"818\" height=\"280\" class=\"aligncenter size-full wp-image-15005\" \/>\n<strong>NOTE:<\/strong> There is a known issue where Code Coverage will not work in C++ unless <em>\/DEBUG:FULL<\/em> is selected as the debugging configuration. By default, the configuration is set to <em>\/DEBUG:FASTLINK<\/em> instead. You can switch to <em>\/DEBUG:FULL<\/em> by doing the following: <\/p>\n<ol>\n<li>Right-click the test project and choose <em>Properties<\/em>.<\/li>\n<li>Go to <em>Linker &gt; Debugging &gt; Generate Debug Info<\/em>.<\/li>\n<li>Set the option to <em>Generate Debug Information optimized for sharing and publishing (\/DEBUG:FULL)<\/em>. <\/li>\n<\/ol>\n<p>The Code Coverage Results window provides an option called <em>Show Code Coverage Coloring<\/em>, which colors the code based on whether it\u2019s covered or not. \n<img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/code-coverage-coloring.png\" alt=\"Image Code Coverage coloring\" width=\"387\" height=\"306\" class=\"aligncenter size-full wp-image-15015\" \/>\nCode coverage is counted in blocks, with a block being a piece of code with exactly one entry and exit point. If a block is passed through at least once, it is considered covered. <\/p>\n<p>For more information on C++ unit testing, including some more advanced topics, check out the following MSDN articles: <\/p>\n<ul>\n<li><a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/hh598953.aspx\">Writing Unit tests for C\/C++ with the Microsoft Unit Testing Framework for C++<\/a><\/li>\n<li><a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/hh419385.aspx\">Unit testing existing C++ applications with Test Explorer<\/a><\/li>\n<li><a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/dd537628.aspx\">Using Code Coverage to Determine How Much Code is being Tested<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Testing is an increasingly important part of a software development workflow. In many cases, it is insufficient to test a program simply by running it and trying it out \u2013 as the scope of the project gets more involved, it becomes increasingly necessary to be able to test individual components of the code on a [&hellip;]<\/p>\n","protected":false},"author":1063,"featured_media":35994,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-14955","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cplusplus"],"acf":[],"blog_post_summary":"<p>Testing is an increasingly important part of a software development workflow. In many cases, it is insufficient to test a program simply by running it and trying it out \u2013 as the scope of the project gets more involved, it becomes increasingly necessary to be able to test individual components of the code on a [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/posts\/14955","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/users\/1063"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/comments?post=14955"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/posts\/14955\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/media\/35994"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/media?parent=14955"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/categories?post=14955"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/tags?post=14955"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}