开发者

gmock : Doing custom check that can fail

I am using google mock library in my unit tests, and I am trying to do a custom check that can fail.

Next example demonstrates what I am trying to do :

struct Base
{
};
struct Derived : Base
{
  int a;
};

struct MockClass
{
  MOCK_METHOD1( Send, void ( Base & ) );
};

Now I would like to check if the fake object got passed object of type Derived in the Send method, and the value a. So, how to do it?

My idea is to use Invoke and forward the call to some function, which will dynamic_cast from Base to Derived, and check the value. If the type is not of expected throw an exception. Like this :

void TestCall( Base &obj )
{
  Derived *realObj = dynamic_cast< Derived * >( &obj );
  if ( NULL == realObj )
  {开发者_运维知识库
    throw 123;
  }
}

then test like this :

MockClass mockObj;
EXPECT_CALL( mockObj, Send(_) )
  .WillOnce( Invoke( &TestCall ) );

Is this going to work? Or is there a better way?


You can define a custom matcher to verify the type and the value of your argument simultaneously:

MATCHER_P(IsDerivedAnEqual, a, "") {
  Derived* derived_arg = dynamic_cast<Derived*>(&arg);
  return derived_arg != NULL && derived_arg->a == a;
}

EXPECT_CALL(mock_obj, Send(IsDerivedAndEqual(5));

You can also use composite matchers to build more complex conditions.

Calls you put into the WillOnce() expression are actions. They are only invoked if a call matches the expectations you have set and are supposed to mimic what an external dependency would do if invoked. Using them to set expectations will not work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜