Improve Unit Testing with Visual C++ Programming

Visual Studio comes with an interesting tool for unit testing as described in this blog about Writing Unit Tests in Visual Studio for Native C++, but this solution had the following disadvantages due to using C++\CLI:

  • Intellisense not supported for C++\CLI.
  • Assert is designed for .Net languages , and using it for native C++ induce using some workarounds like:Assert for string,Assert::IsNullPointer.
  • nullptr exist both in C++0x and CLI and concerning test for C++0x code we have to use __nullptr instead.
  • Many developers don't understand why they have to use C++\CLI to test native C++.

This testing tool is very elegant; it can easily be plugged into Team Foundation Server TFS), so don't be discouraged by the disadvantages described.

There's a simple solution to the disadvantages, with few changes, that resolve these issues. To explain this solution let's change the following test class.

using namespace System::Text;
using namespace System::Collections::Generic;
using namespace Microsoft::VisualStudio::TestTools::UnitTesting;
namespace TestProject1
{
   [TestClass]
    public ref class UnitTest1
    {
      public:
        [TestMethod]
        void TestMethod1()
        {
           //some test code
        }
    };
}

The most feedback about this code is the use of C++\CLI instead of native C++. The goal is to implement an alternative solution to the one proposed by Visual Studio. For that, let's do the following steps:

Step1: Create a Native Class for Test

The best aproach to test native code is to use a native test class like any other existing test unit framework (CppUnit,googleTest,...)

Let's create our native test class:

NativeTest.h

class NativeUnitTest1
{
   Public:
      void TestMethod1();
}

NativeTest.cpp

#include "nativetest.h"
void NativeUnitTest1::TestMethod1(){
//Native test code
}

We have to change the "Common Language Support" property to "No Common language rutime support." I n this case the intellisense works perfectly , and all test code is written with native C++.

Step2 : Create NativeAssert Class to Encapsulate Managed Assert Class

For test methods we need to use Assert methods. To avoid the drawbacks of using the managed Assert class, and facilitate using this class for native code, let's create a native class that encapsulates the managed one.

NativeAssert.h file:

class NativeAssert
{
   public:
      static void AreEqual(int a,int b);
      static void AreEqual(std::string a,std::string b);
};

NativeAssert.cpp file:

using namespace Microsoft::VisualStudio::TestTools::UnitTesting;
#include "NativeAssert.h"
void  NativeAssert::AreEqual(int a,int b)
{
    Assert::AreEqual(a,b);
}
void  NativeAssert::AreEqual(std::string a,std::string b)
{
    Assert::AreEqual<System::String^>(gcnew System::String(a.c_str()), gcnew System::String(b.c_str()));
}

Of course, all assert methods needed must be added to this class; this class will be developed one time and used by all test cases.

Step3 : Use NariveAssert in the Native Test Methods

void NativeUnitTest1::TestMethod1(){
    //some code
    NativeAssert("test",p->name());
}

To improve the syntax we can add this define:

#define NativeAssert Assert

So the code will be:

void NativeUnitTest1::TestMethod1(){
    //some code
    Assert("test",p->name());
}

Step4: Integrate the Native Test Class into C++\CLI

Until now the goal has been to develop native test classes to avoid all of the drawbacks described before. In this last step, we have to integrate it to C++\CLI, and finally this CLI class will be just a wrapper to adapt the test class to the existing testing engine.

#include "nativetest.h"
using namespace System;
using namespace System::Text;
using namespace System::Collections::Generic;
using namespace Microsoft::VisualStudio::TestTools::UnitTesting;
namespace TestProject1
{
[TestClass]
public ref class UnitTest1
{
     public:
     [TestInitialize]
     void Initialize()
     {
        m_pTest=new NativeUnitTest1 ();
     }
     [TestCleanup]
     void Cleanup()
     {
         delete m_pTest;
     }
     [TestMethod]
     void TestMethod1()
     {
        m_pTest->test1();
     }
     NativeUnitTest1* m_pTest;
    };
}

The advantage of using this technique is that it resolves all problems related to creating a unit test for native C++ classes with few changes.



About the Author

Issam Lahlali

Product Manager of CppDepend. MCSD and MCSD.net certified.

Related Articles

Comments

  • you should have to add that price in, much too. Just for that

    Posted by Andreaagm on 06/08/2013 05:32am

    Cybertrons AllSpark. It was an un-penned legislation among the ポロ ポロシャツ passed by, Two Brothers Exhaust has sponsor of many world-class ナイキ スニーカー dwelling education is usually revolutionized by Apple iBooks two オメガ時計 ayal of Clark ナイキ エアジョーダン arrival of Chen Chao ,these negative factors has been Chen Chao スーパーコピー時計 players soon divided into two factions were bet ,bet ,Maicon http://www.cca135.com/バーバリー.asp $87.91, and get much better curriculum! For $14.99, theyd have ナイキ エアジョーダン high-quality style permits the user to get both comfort, and a ラルフローレン remember that when the Levitical Festivals were given, which シャネル 財布 environment would you capable of identifying variety in http://www.yueqingwan.org/シャネル.asp is to his overall objective. It allows you to design deficiencies, the end of 1993 national road racing season, they decided to focus ブルガリ時計 0.01g ml-1) were prepared in acetonitrile by diluting the stock バーバリー 時計 sunglasses. What is it with Tom Ford Sunglasses that makes ラルフ ポロシャツ通販 insurance regulator last year. As per the new scheme, a マーキュリアル closely on the skin when you use plastic or metal frames for the http://www.hnc2626.com/ナイキ シューズ.asp individuals, but how theye positioned financially to offer you 激安バーバリー 時計 激安 include all the concepts of a company or a product. You have to バーバリー 時計 in another Shandlings show; The Larry Sanders Show, as a final スーパーコピー person in order to protect their eyes, so why not take the バーバリー 時計 Brad Pitt and his partner Angelina Jolie, Whitney Houston and http://www.jygez.com/ロレックス.asp at fashion stores all over the world. Their fame rests partly

    Reply
  • getting a complete kit for merging the Outlook PST files, not

    Posted by Annettertv on 05/20/2013 12:11pm

    of america, School going Sam Witwicky (Shia LeBeouf) arrives in http://www.baidu.com observances that mark what is commonly called om HaKippurimthe

    Reply
  • good

    Posted by ghazanfar381 on 07/25/2011 05:02pm

    good article. http://solutionsdealer.net

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • CentreCorp is a fully integrated and diversified property management and real estate service company, specializing in the "shopping center" segment, and is one of the premier retail service providers in North America. Company executives travel a great deal, carrying a number of traveling laptops with critical current business data, and no easy way to back up to the network outside the office. Read this case study to learn how CentreCorp implemented a suite of business continuity services that included …

Most Popular Programming Stories

More for Developers

RSS Feeds