Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching arguments of custom type in googlemock

Tags:

c++

googlemock

I have a problem matching a function argument to a specific object using google mock.

Consider the following code:

class Foo
{
public:
    struct Bar
    {
        int foobar;
    }

    void myMethod(const Bar& bar);
}

Now I have some testing code, it could look like this:

Foo::Bar bar;
EXPECT_CALL(fooMock, myMethod(Eq(bar));

So I want to make sure that when Foo::myMethod is called, the argument looks like my locally instantiated bar object.

When I try this approach I get an error message like:

gmock/gmock-matchers.h(738): error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const Foo::Bar' (or there is no acceptable conversion)

I tried playing around with defining operator == and != (at least == both as member of free function), using Eq(ByRef(bar)) but I could not fix the issue. The only thing that helps is using

Field(&Foo::Bar::foobar, x) 

but this way I have to check every field in my struct which seems like a lot of typing work...

like image 893
anhoppe Avatar asked Jun 21 '13 10:06

anhoppe


People also ask

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) .

How do you mock in Gmock?

first, you use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; next, you create some mock objects and specify its expectations and behavior using an intuitive syntax; then you exercise code that uses the mock objects.

What is Googlemock?

Gmock is a mocking framework for the Groovy language. Gmock is all about simple syntax and readability of your tests so you spend less time learning the framework and more writing code. To use Gmock just drop the gmock jar file in your classpath. The current version is gmock-0.8. 3 and is packed with tons of feature.


1 Answers

Ok, then I'll answer to myself:

You have to provide an operator== implementation for Foo::Bar:

bool operator==(const Foo::Bar& first, const Foo::Bar& second)
{
    ...
}

Don't add it as member function to Foo::Bar but use a free function.

And, lessons learned, be careful to NOT put them into an anonymous namespace.

like image 114
anhoppe Avatar answered Sep 18 '22 08:09

anhoppe