如何解决Googlemock 暂停预期
我有一个场景,我希望对模拟对象上的函数进行一些调用,然后对于某些代码路径,我需要确保不调用该函数,然后调用它。有没有办法做到这一点?
EXPECT_CALL(mockObj,1);
foo(1);
// Expect this call at the first invocation of foo(2)
EXPECT_CALL(mockObj,2);
foo(2);
// These calls should not call my mockObj again,the above expectation is
// intended for the first invocation of foo(2)
foo(2);
foo(2);
// And Now,i expect it to be called
EXPECT_CALL(mockObj,3);
foo(3);
我可能会检查 EXPECT_CALL(mockObj,2);只被调用了预期的次数,但我也想确认它只在第一次调用 foo(2) 时调用,而不是在后续调用 foo(2) 时调用。 你能告诉我在 gmock 中实现这一目标的任何方法吗?
解决方法
Gmock cookbook 建议使用虚拟检查点模拟函数
using ::testing::MockFunction;
TEST(FooTest,InvokesMyMockCorrectly) {
MyMock mockObj;
// Class MockFunction<F> has exactly one mock method. It is named
// Call() and has type F.
MockFunction<void(string check_point_name)> check;
{
InSequence s;
EXPECT_CALL(mockObj,1);
EXPECT_CALL(check,"1");
EXPECT_CALL(mockObj,2);
EXPECT_CALL(check,"2");
EXPECT_CALL(check,"3");
EXPECT_CALL(mockObj,3);
}
foo(1);
check.Call("1");
foo(2);
check.Call("2");
foo(2);
foo(2);
check.Call("3");
foo(3);
}
或者使用 Mock::VerifyAndClearExpectations() 重置模拟,然后设置新的期望。
否则在某些答案中建议对模拟和 EXPECT_CALL 的调用交错调用是未定义的行为:
重要说明:gMock 要求在调用模拟函数之前设置期望值,否则行为未定义。特别是,您不能将 EXPECT_CALL() 和对模拟函数的调用交织在一起。
来自gmock for dummies,另见Interleaving EXPECT_CALL()s and calls to the mock functions
,我会把它分成几个测试用例:
TEST(Foo,CalledOnFirstInvoation) {
EXPECT_CALL(mockObj,1);
foo(1);
}
TEST(Foo,CalledAgainWhenUsingDifferenArgument) {
EXPECT_CALL(mockObj,2);
foo(1);
foo(2);
}
TEST(Foo,NotCalledWhenUsingSameArgument) {
EXPECT_CALL(mockObj,2);
foo(1);
foo(2);
foo(2);
foo(2);
}
TEST(Foo,CalledAgainWhenUsingYetAnotherArgument) {
EXPECT_CALL(mockObj,3);
foo(1);
foo(2);
foo(2);
foo(3);
}
,
你想要这样的东西吗?
EXPECT_CALL(mockObj,1).Times(0);
EXPECT_CALL(mockObj,2).Times(0); // #2
EXPECT_CALL(mockObj,3); // #3
{
EXPECT_CALL(mockObj,1); // #1
foo(1); // Matches #1
}
{
EXPECT_CALL(mockObj,2); // #4
// Expect this call at the first invocation of foo(2)
foo(2); // Matches #4
}
// These calls should not call my mockObj again,the above expectation is
// intended for the first invocation of foo(2)
foo(2); // Matches #2
foo(2); // Matches #2
// And now,i expect it to be called
foo(3); // Matches #3
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。