12

Just getting into Unit Testing with C++. It looks like I will need to write several stub classes as I go along. My understanding is there is a difference between Mocks and Stubs. Basically it seems Mocks are for when you are testing something happened on the object (e.g. verifying) while Stubs just facilitate your test. I guess for mocking, I can use googlemock but I don't see anything in it for creating Stubs (ala RhinoMocks' GenerateStub).

Is there a way to get automatically generated stubs? Does googlemock have any support for stubs? Or do I pretty much have to manually create stubs for testing?

4

4 回答 4

18

我认为这个难题的缺失部分是您不必对方法设置期望,而是可以设置默认返回值。

模拟

“ Google Mock for Dummies ”中的所有讨论和示例都集中在设定期望上。一切都在谈论使用类似于以下的代码:

EXPECT_CALL(turtle, PenDown())
      .Times(AtLeast(1));

这是你想要嘲笑的,但对于存根你没有任何期望。在阅读了该介绍之后,我不知道如何使用 googlemock 进行存根。

存根

ratkok 的评论让我了解了如何设置默认返回值。以下是如何为模拟对象指定返回值但不期望:

ON_CALL(foo, Sign(_))
      .WillByDefault(Return(-1));

https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#setting-the-default-actions-for-a-mock-method

如果您调用没有 EXPECT_CALL 的方法,googlemock 似乎会发出警告。显然你可以通过使用他们的NiceMock构造来防止这个警告,或者你可以忽略它。此外,您似乎可以通过使用 expect 来避免警告(我不确定这对于存根是否是个好主意)。来自Google Mock 常见问题解答

EXPECT_CALL(foo, Bar(_))
    .WillRepeatedly(...);

我相信这正是我想要弄清楚的。

更新

我可以确认这是有效的。我使用 google test 和 googlemock 编写了一个单元测试,并且能够使用 ON_CALL 为一个类生成一个方法。

于 2011-06-15T14:47:40.810 回答
3

Mock 和 Stub 之间的唯一区别是 Mock 强制执行行为,而 Stub 没有。

据我所知,默认情况下,Google Mock 的模拟实际上是存根。如果您在各种方法上放置断言,它们只会强制执行行为。

于 2011-06-14T23:44:21.013 回答
0

看看这个:stubgen和这里的类似讨论。

这个问题也可能有用/相关。

关于谷歌模拟 - 我们在我当前的项目中使用它来完全自动化存根实现。实际上,整个存根代码库都是使用 google mocks 实现的。

于 2011-06-15T13:00:07.390 回答
0

https://github.com/coolxv/cpp-stub

//for linux and windows
#include<iostream>
#include "stub.h"
using namespace std;
int foo(int a)
{   
    cout<<"I am foo"<<endl;
    return 0;
}
int foo_stub(int a)
{   
    cout<<"I am foo_stub"<<endl;
    return 0;
}


int main()
{
    Stub stub;
    stub.set(foo, foo_stub);
    foo(1);
    return 0;
}
于 2021-06-29T03:30:02.123 回答