Search code examples
c++tddraii

Howto mix TDD and RAII


I'm trying to make extensive tests for my new project but I have a problem.

Basically I want to test MyClass. MyClass makes use of several other class which I don't need/want to do their job for the purpose of the test. So I created mocks (I use gtest and gmock for testing)

But MyClass instantiate everything it needs in it's constructor and release it in the destructor. That's RAII I think.

So I thought, I should create some kind of factory, which creates everything and gives it to MyClass's constructor. That factory could have it's fake for testing purposes. But's thats no longer RAII right?

Then what's the good solution here?


Solution

  • You mock it the same way you'd mock any other class. Have the RAII class' constructor take care of it.

    class MyInterface
    {
        virtual void MyApiFunction(int myArg)
        {
            ::MyApiFunction(myArg);
        }
    };
    
    class MyRAII : boost::noncopyable //Shouldn't be copying RAII classes, right?
    {
        MyInterface *api;
    public:
        MyRAII(MyInterface *method = new MyInterface)
        : api(method)
        {
            //Aquire resource
        }
        ~MyRAII()
        {
            //Release resource
            delete api;
        }
    };
    
    class MockInterface : public MyInterface
    {
        MOCK_METHOD1(MyApiFunction, void(int));
    };
    
    TEST(Hello, Hello)
    {
        std::auto_ptr<MockInterface> mock(new MockInterface);
        EXPECT_CALL(*mock, ....)...;
        MyRAII unitUnderTest(mock.release());
    }