Unittesting private data and members with VS2012

Answered Unittesting private data and members with VS2012

  • Friday, September 14, 2012 8:02 PM
     
      Has Code

    Hello again,

    I want to Unit-Test private data and members from a project, that creates a static library(.lib).

    So i followed the instructions in this tutorial http://msdn.microsoft.com/en-us/library/hh419385#staticLink

    But when i do the following:

    TEST_CLASS(UnitTest1)
    	{
    	public:
    		
    		TEST_METHOD(Test_InitToZero)
    		{
    			Inc::IncHandle<HANDLE, handle_traits> TestHandle;
    
    			Assert::AreEqual((HANDLE)nullptr, TestHandle.m_TheHandle);
    		}
    
    	};

    the compiler creates an error saying that m_TheHandle is private and cannot be accessed...

    Anyone got a clue what i've done wrogn, and how to fix this?

    With regards,
    Inc

All Replies

  • Saturday, September 15, 2012 6:21 AM
     
     
    Well, in regular C++ you can make a class a friend of another class by means of the friend keyword.  Try it out.

    Jose R. MCP
    Code Samples

  • Saturday, September 15, 2012 10:34 AM
     
     

    Does it mean, that what is stated in http://msdn.microsoft.com/en-us/library/hh419385.aspx#objectRef as "private functions and data" is not meant to be class-stuff but data and functions which are not exported/made accessible by the library?

  • Saturday, September 15, 2012 11:16 AM
     
     Answered Has Code

    Does it mean [...] not [...] class-stuff but data and functions which are not exported/made accessible by the library?

    Yes, exactly.  If your unit tests really do need to access private members of the classes under test, you'll need to use some hack to allow that.  One is to make your unit test classes friends of the classes under test:

    class IncHandle
    {
        friend class UnitTest1;
        // ...
    };

    A quick-and-dirty alternative, which is a horrible but does the job, is this nasty-but-widely-used aberration:

    #define private public
    #include "inchandle.h"
    #undef private

    But you should be asking yourself why you want to access private data at all?  In your example, might it be sensible to add a public member something like this:

    class IncHandle { public: bool hasHandle() { return mc_TheHandle != nullptr; }

    // ... }


    and then call that from your test:

    Assert::IsFalse(TestHandle.hasHandle());