fluter
fluter

Reputation: 13786

Gmock matcher to match against type

In gmock is there anyway to match against a type rather than value? The class is something like:

struct Blob {
    template<class T> bool is(); // if blob holds data of type T
    template<class T> T get(); // get data as type T
}

My matcher looks like this:

MATCHER_P(BlobIs, T, "") {
    return arg->is<T>();
}

But the build failed with:

error: expected primary-expression before ')' token

Upvotes: 3

Views: 5572

Answers (2)

pooya13
pooya13

Reputation: 2691

You can use wildcard matchers A<type> and An<type> (documentation):

EXPECT_CALL(foo, Describe(A<const char*>()))
    .InSequence(s2)
    .WillOnce(Return("dummy"));

Upvotes: 3

PiotrNycz
PiotrNycz

Reputation: 24402

You cannot pass type as parameter to any function - including those generated by MATCHER_P macro.

But you can pass lambda(function object) that will use correct type.

Like here:

MATCHER_P(BlobIsImpl, isForForType, "") {
    return isForType(arg);
}

With the following function template - you will achieve the desired goal:

template <typename T>
auto BlobIs()
{
     auto isForType = [](Blob& arg) -> bool 
     { 
         return arg->template is<T>();
     };
     return BlobIsImpl(isForType); 
}

Use like this: BlobIs<SomeType>()

2 more issues:

  1. You have to use template keyword to specify that is is a function template. More info here
  2. You should define is as const function.

Upvotes: 2

Related Questions