Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic generation of mock classes for gmock

I am using gmock for unit testing C++ code. I am not using the gtest framework. I am using visual studio 2008's built-in testing framework.

Now my problem is that I have to manually write mock classes for a real class to unit test. For example if I have A class with 5 functions then I have to write MockAClass with 5 functions. Is there any way that these classes are automatically generated.

class AClass
{
public:
    virtual int AFunction()
    {
        return 5;
    }
    virtual int AFunctionWithArguments(int x)
    {
        return x;
    }



class MockAClass : public AClass
{
public:
    MOCK_METHOD0(AFucntion, int());
    MOCK_METHOD1(AFunctionWithArgument, int(int x));
};
like image 322
fhnaseer Avatar asked Feb 13 '12 07:02

fhnaseer


People also ask

How do you make a mock gMock?

Using the Turtle interface as example, here are the simple steps you need to follow: Derive a class MockTurtle from Turtle . Take a virtual function of Turtle (while it's possible to mock non-virtual methods using templates, it's much more involved). In the public: section of the child class, write MOCK_METHOD();

How do you mock a function in gMock?

Mocking Free Functions It is not possible to directly mock a free function (i.e. a C-style function or a static method). If you need to, you can rewrite your code to use an interface (abstract class).

What is Gtest and gMock?

In real system, these counterparts belong to the system itself. In the unit tests they are replaced with mocks. Gtest is a framework for unit testing. Gmock is a framework imitating the rest of your system during unit tests.

What is expect call in gMock?

In gMock we use the EXPECT_CALL() macro to set an expectation on a mock method. The general syntax is: EXPECT_CALL(mock_object, method(matchers)) . Times(cardinality) . WillOnce(action) .


1 Answers

There is a tool bundled with the google mock project that will help you do this. However I think the tool requires python to be installed, and I don't know how well it works in a windows environment. I've also found that the generated files sometimes need a little tweak to work perfectly.

Here's the info from the docs:

Tip: If even this is too much work for you, you'll find the gmock_gen.py tool in Google Mock's scripts/generator/ directory (courtesy of the cppclean project) useful. This command-line tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it, and it will print the definition of the mock class for you. Due to the complexity of the C++ language, this script may not always work, but it can be quite handy when it does. For more details, read the user documentation.

Here is new localization of this script.

like image 63
Michael Anderson Avatar answered Oct 17 '22 17:10

Michael Anderson