Paul Dubsky
Paul Dubsky

Reputation: 177

Unit test for public method that returns pointer to a private member

I have such code:

class Foo
{
private :

    int m_nValue;

public :

    explicit Foo(const int nValue) : 
        m_nValue(nValue)
    {
    }

    const int* Pointer() const
    {
        return &m_nValue;
    }
};

void Test()
{
    Foo obj(3);

    // I want to do something like this.
    //Assert::AreEqual(&obj.m_nValue, obj.Pointer());
}

I want to test Pointer() method that returns an address of the private field m_nValue. Can someone please help with some nice solution for this situation. I can make testing class/function a friend but I really don't like it.

Maybe it's not the method that should be tested. But as far as I know all public method should be tested.

Tests are written in C++ for C++ code in MSVS 2012

Upvotes: 1

Views: 651

Answers (2)

Thomas
Thomas

Reputation: 5148

You should not be testing the internals of the class just its observable behavior. The test should be

Asser::AreEqual( *obj.Pointer(), 3 ); 

Upvotes: 3

Andrew White
Andrew White

Reputation: 53516

I always advise to not test trivial behavior. I would classify this as trivial. In the Java world this is akin (not exactly but close) to testing a getter which Martin from Clean Code advises against.

The best you could do is test that the pointer is not null and that its dereferenced value is what you expect.

Upvotes: 0

Related Questions