0

I'm having a crash in the following code:

class ITest
{
    virtual void test(){};
};


void doNothing(){}



class TestMock: ITest
{
public:
    MOCK_METHOD0(test, void());
};


class Server_Fixture: public ::testing::Test
{
public:
    std::unique_ptr<TestMock> mock;

    void SetUp() override
    {        
        mock = std::unique_ptr<TestMock>();
    }

    void TearDown() override
    {

    }

    TestMock& getMock(){ return *mock; }
};


TEST_F(Server_Fixture, execute)
{
    EXPECT_CALL(getMock(), test()).WillRepeatedly(Invoke(doNothing)); // <<<< Segmentation fault (core dumped)
}

Could someone explain why it is crashing ? The crash does not happen if I create a local mock object (without using unique_ptr) in the TEST_F function.

Quarra
  • 2,023
  • 1
  • 16
  • 25
HAL9000
  • 3,169
  • 2
  • 22
  • 43
  • I don't remember what's actually inside those TEST_F macros at the moment so I'd try adding a Server_Fixture constructor and destructor. Then add log outputs (or printf or cout, whatever) to the constructor, destructor and SetUp and TearDown and getMock functions. See if it gets destroyed before it gets used. – Zan Lynx Oct 09 '20 at 20:38
  • 2
    `mock = std::unique_ptr();` should be `mock = std::make_unique();`. – RA. Oct 11 '20 at 20:20
  • @RA. thanks for the suggestion, this is solving the issue. Would you have some resources about the difference between the two? I remember I read somewhere that they should be equivalent. – HAL9000 Oct 12 '20 at 06:29
  • 1
    @HAL9000 The default constructor always constructs a `unique_ptr` that owns nothing (see https://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr). See also: https://stackoverflow.com/questions/22571202/differences-between-stdmake-unique-and-stdunique-ptr-with-new – RA. Oct 12 '20 at 21:23

0 Answers0