【问题标题】:Google test : EXPECT_CALL fails to compile in my test code谷歌测试:EXPECT_CALL 无法在我的测试代码中编译
【发布时间】:2015-07-22 03:55:08
【问题描述】:

我正在使用 gmock 尝试我的第一个 google 测试,准备好所有 VS 环境。 gtest ASSERT_XX 函数的简单用法有效。但是在尝试使用 gmock 时,我遇到了第一个编译问题。我想也许我的程序有问题,但 gtest 没有告诉我如何解决它。

在下面的程序中,我得到了一个名为“FileIo”的类。它的“读取”函数将执行 I/O,我希望模拟这个 Read() 函数,同时保持 f() 和 g() 不变。于是我用 NickMock 建立了一个 FileIo 的 mock 对象,然后尝试用 EXPECT_CALL 来伪造一个 Read() 函数。

class FileIo
{
public:
    int f(){ return 1; }
    int g(int i){ return i*i; }
    int Read(){
        FILE* pf = fopen("D:\\a.txt", "r+w");
        fclose(pf);
        return 3;
    }
};

class BBTest : public ::testing::Test
{
public:

};
TEST_F(BBTest, testcase_1)
{
    NiceMock<FileIo> mio;
    EXPECT_CALL(mio, Read()).WillRepeatedly(DoAll(Return(2)));
}

EXPECT_CALL 语句编译失败。如何解决? 谢谢。

【问题讨论】:

标签: c++ unit-testing mocking googletest


【解决方案1】:

这是您发布的内容的一个非常简单的示例。我不会解释,因为它是最简单的形式。有很多例子可供你学习。谷歌是你最好的朋友。搜索、阅读和学习。

class IFileIo
{
public:
    virtual int Read() = 0;
};

class FileIo : IFileIo
{
public:
    int Read() {
        FILE* pf = fopen("D:\\a.txt", "r+w");
        fclose(pf);
        return 3;
    }
};

class MyClass
{
public:
    void ReadFile()
    {
        _file->Read();
    }
    IFileIo* _file;
};

class NiceMock : public IFileIo
{
public:
    MOCK_METHOD0(Read, int());
};


class BBTest : public ::testing::Test
{
public:
    NiceMock _mio;
};

TEST_F(BBTest, testcase_1)
{
    EXPECT_CALL(_mio, Read()).WillOnce(Return(2));
    MyClass mc;
    mc._file = &_mio;
    mc.ReadFile();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多