googletest - 模拟摘要 class

googletest - mocking abstract class

我正在学习模拟并使用 googletest 我创建了 MockServer class 应该模拟抽象 class IServer:

    class IServer
{
    virtual void writeData(QString buffer) = 0;
    virtual QByteArray readData() = 0;

protected:
    virtual ~IServer() = default;
};

class MockServer: public:: testing:: Test, public IServer
{
    MOCK_METHOD(void, writeData, (QString buffer), (override));
    MOCK_METHOD(QByteArray, readData, (), (override));
};

现在想测试另一个使用它的 class,但是,我无法初始化 MockServer,因为它是一个抽象 class。如何解决?

TEST_F(Serv_test, start)
{
    ?? MockServer mockServer; // <- how to declare it?
    EXPECT_CALL(mockServer, writeData(testing::_)).Times(1);
    EXPECT_CALL(mockServer, readData()).Return("testing");

    Car car (nullptr, mockServer);
}

你混淆了一些事情:

  1. 您正在使用测试夹具,但测试夹具需要是独立的 class。你把它和你的 mock class 混在一起了。您需要为其创建一个单独的 class。

  2. Car class 应该采用 mock class 类型的参数(不是测试夹具)。

  3. .Return 应在 WillOnceWillRepeatedly 等其他地方使用。您不能直接在 EXPECT_CALL.

    上使用它

我重写了你的代码如下:

class IServer
{
  public:
    virtual void writeData(QString buffer) = 0;
    virtual QByteArray readData() = 0;

protected:
    virtual ~IServer() = default;
};

// Test fixture
class Serv_test : public ::testing::Test {
};

// Mock class
class MockServer: public IServer
{
 public:
    MOCK_METHOD(void, writeData, (QString buffer), (override));
    MOCK_METHOD(QByteArray, readData, (), (override));
};

class Car{
  public:
  Car(int*, IServer* server):_server(server){
      _server->writeData("testing");
      _server->readData();
  }

  IServer* _server;
};

TEST_F(Serv_test, start)
{
    MockServer mockServer; // <- how to declare it?
    EXPECT_CALL(mockServer, writeData(testing::_)).Times(1);
    EXPECT_CALL(mockServer, readData())
      .WillOnce(testing::Return("testing"));

    Car car (nullptr, &mockServer);
}

这里的工作示例:https://godbolt.org/z/avsKdh37r