当其中一个模拟方法被调用时,我正在学习gmock,并想知道如何才能让模拟对象做一些事情。
我需要模拟一些使用Qt的接口,并且我正在尝试让Qt和Gmock一起工作。
例如,我模拟了一个网络套接字接口类,通过基于DI的构造函数将它交给了一个网络客户端类,我想告诉模拟套接字调用它的方法之一,在连接完成时向客户机发送信号,以便假装连接已经建立。
我看到了WillOnce,它需要和“操作”,但我正在阅读的文档并没有真正解释“动作”可以是什么类型的东西。所有的例子都只是返回一些东西或增加一个全局变量。您能调用属于您正在模拟的抽象类的方法吗?
如果不是,我看到您可以单独定义一个假对象,并使其成为模拟的成员,然后委托,但在每个需要不同行为的测试用例中,这似乎是一项艰巨的工作。
中发出信号。
下面是一些示例代码:
class MySocketInterface : QObject
{
Q_OBJECT
public:
virtual void connect(std::string url) = 0;
signal: // Specific to Qt, but this is what I need to call
// Notifies subscribers
void connected();
}
class MyThingToTest
{
public:
MyThingToTest(std::unique_ptr<MySocketInterface> && socket);
void connect(std::string url);
State getState() const;
private:
std::unique_ptr<MySocketInterface> m_socket;
// Changes state to connected
void onConnected();
}
Test1:
) Make a mock socket
) Give it to MyThingToTest
) Call MyThingToTest::connect
) mock socket needs to send notification faking connecting by calling `emit connected`
) Check if MyThingToTest is in connected state
Test2:
) Make a mock socket
) Give it to MyThingToTest
) Call MyThingToTest::connect
) mock socket needs to not send notification, and 30 seconds needs to elapse.
) Check if MyThingToTest is in an error state我希望避免不得不定义一个全新的假类,并模拟每个操作不同的单元测试用例。
请注意,我不是寻找QSignalSpy或验证信号和插槽。我想验证我的类的功能,这些类对它们有反应,并且让这些类使用模拟依赖关系,这样我就不必在真实的网络上交谈了。
发布于 2021-05-27 16:33:23
假设您使用的是Qt 5或更高版本,您应该能够使用InvokeWithoutArgs来实现您想要的结果。您的模拟对象应该定义如下:
class MockMySocketInterface : public MySocketInterface
{
Q_OBJECT
public:
MockMySocketInterface() { }
virtual ~MockMySocketInterface() { }
MOCK_METHOD1(connect, void(std::string));
};您的测试结果如下所示:
auto socket = std::make_unique<MockMySocketInterface>(); // Could also use NiceMock here.
// This could alternately be an EXPECT_CALL, but you would need to use WillOnce
// or WillRepeatedly instead of WillByDefault.
ON_CALL(*socket, connect(_))
.WillByDefault(InvokeWithoutArgs(socket.get(), &MockMySocketInterface::connected));
MyThingToTest thing(socket);
// etc.https://stackoverflow.com/questions/67722938
复制相似问题