eranpeer / FakeIt

C++ mocking made easy. A simple yet very expressive, headers only library for c++ mocking.
MIT License
1.22k stars 170 forks source link

Unknown exception after Mock an object method #244

Closed regisf closed 2 years ago

regisf commented 3 years ago

Similar with the issue #20 Let's take a small code bellow. I which to ensure that the method one calls the method two to avoid side effect. In my program the equivalent to the method two process an IO, which is not desired in test mode.

#include <gtest/gtest.h>
#include <fakeit.hpp>

using namespace fakeit;

class IMyClass
{
public:
        virtual void one() = 0;
        virtual void two() = 0;
};

class MyClass : public IMyClass
{
public:
        virtual void one()
        {
                two();
        }

        virtual void two()
        {
                std::cout << "Hello\n";
        }
};

TEST(test_fakeit, test_fakeit)
{
        // Arrange
        MyClass myClass;
        Mock<MyClass> spy(myClass);

        When(Method(spy, two));

        // Act
        myClass.one();

        // Assert
        Verify(Method(spy, two)).Exactly(1_Time);
}

int main(int argc, char** argv)
{
    ::testing::InitGoogleTest(&argc, argv);

    return RUN_ALL_TESTS();
}

The test crash with

[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from test_fakeit
[ RUN      ] test_fakeit.test_fakeit
unknown file: Failure
Unknown C++ exception thrown in the test body.
[  FAILED  ] test_fakeit.test_fakeit (1 ms)
[----------] 1 test from test_fakeit (1 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (2 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] test_fakeit.test_fakeit

I don't know if it's a bug or if I doing it wrong.

Could you help me please ?

malcolmdavey commented 2 years ago

Do you need to add this?

Spy(Method(spy, one)); // Spying one without changing any behavior

// then instead of myClass.one();
spy.one();

Also see docs https://github.com/eranpeer/FakeIt/wiki/Quickstart#spying

regisf commented 2 years ago

@malcolmdavey

Many thanks.

Regards