Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a class with private constructor?

I have a class Foo. I only want to allow Bar to create it, so I make its constructor private and make Bar its friend. But now how can I unit test Foo's public methods (e.g., getValue)? I do not have a way to create its instance in the unit test file.

class Foo final
{
public:
    int getValue();
private:
    friend class Bar;
    Foo(int value);
};

class Bar
{
protected:
    Foo createFoo(int value);
};
like image 699
Fan Avatar asked Sep 12 '25 00:09

Fan


1 Answers

You can add an extra friend class for Unit testing

class Foo final
{
public:
    int getValue();
private:
    friend class Bar;
    friend class UnitTests; // Here
    Foo(int value);
};

class UnitTests {
public:
     bool constructor_ok() { Foo test_instance(42); ... }
};
like image 85
Kostas Avatar answered Sep 14 '25 13:09

Kostas