gmock:进行可能失败的自定义检查
我在单元测试中使用谷歌模拟库,并且我正在尝试进行可能失败的自定义检查。
下一个示例演示了我想要做的事情:
struct Base
{
};
struct Derived : Base
{
int a;
};
struct MockClass
{
MOCK_METHOD1( Send, void ( Base & ) );
};
现在我想检查假对象是否在 Send 方法中传递了 Derived 类型的对象以及值 a。 那么,该怎么做呢?
我的想法是使用 Invoke 并将调用转发到某个函数,该函数将从 Base 动态转换为 Derived,并检查值。如果类型不是预期的,则抛出异常。像这样:
void TestCall( Base &obj )
{
Derived *realObj = dynamic_cast< Derived * >( &obj );
if ( NULL == realObj )
{
throw 123;
}
}
然后像这样测试:
MockClass mockObj;
EXPECT_CALL( mockObj, Send(_) )
.WillOnce( Invoke( &TestCall ) );
这会起作用吗?或者有更好的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以定义自定义匹配器来验证类型和同时计算参数的值:
您还可以使用复合匹配器建立更复杂的条件。
您放入
WillOnce()
表达式中的调用是操作。仅当调用符合您设置的期望时才会调用它们,并且它们应该模仿外部依赖项在调用时会执行的操作。用它们来设定期望是行不通的。You can define a custom matcher to verify the type and the value of your argument simultaneously:
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.