c++ - GoogleTest 中的参数化测试未按预期工作

标签 c++ googletest

我刚刚开始学习 googletesting,并且正在使用它。 我想使用参数化测试来检查类的函数成员返回的值是否是它应该的值。 我已经声明了一个名为“myClass”的类,在其中我使用构造函数设置了一个变量的值,我还有一个返回它的值的公共(public)函数“retA()”。

然后我声明了一个 fixture 类,在其中我创建了一个“myClass”的对象 (obj),使用构造函数实例化成员 a,并将 obj.retA() 函数的值分配给一个 int 值“result”。然后我写了一个“TEST_P”,我在其中检查结果是否符合我的预期并实例化 TEST_P。然后我主要开始所有测试。

当我只传递不应使测试失败的参数时,我的测试失败了,我不明白为什么 :((我认为结果应该是 3)

请帮我解决这个问题。谢谢。

#include "stdafx.h"
#include "gtest\gtest.h"
#include "gmock\gmock.h"
#include "Tests.cpp"

class myClass
{
private:
    int a;
public:
    myClass() {}
    myClass(int a) { a = this->a; }
    void setA(int val) { a = val; }
    int retA() { return a; }
};

class myFixture : public ::testing::TestWithParam<int>
{
public:
    int result;

    myFixture()
    {
        myClass obj( GetParam() );
        result = obj.retA();
    }
};

TEST_P(myFixture, Test1) {
    // Inside a test, access the test parameter with the GetParam() method
    // of the TestWithParam<T> class:
    ASSERT_EQ(3, result);
}

INSTANTIATE_TEST_CASE_P(
    InstantiationName, myFixture, ::testing::Values(3);
);

int main(int argc, char** argv)
{
    ::testing::InitGoogleMock(&argc, argv);
    return RUN_ALL_TESTS();

}

最佳答案

您做的一切都非常正确。期待小东西,很难找到......;)

在您的测试类 (myClass) 中,在构造函数中 this 是相反的。它应该看起来像这样:

myClass(int a) { this->a = a; }

关于c++ - GoogleTest 中的参数化测试未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45907988/

相关文章:

c++ - 如何将类型名称传递给函数?

c++ - 用于运行测试和浏览报告的 Eclipse (CDT) 插件

c++ - 为什么 CMAKE 找不到这些变量?

c++ - 支持单个位偏移的类似“memcpy”的函数?

c++ - mongoose web 服务器 helloworld 程序

c++ - 测试项目在访问私有(private)静态方法时出现问题,即使我从未直接调用它

c++ - 如何在函数内 GMOCK 一个函数?

cmake - 使用带有新命令 gtest_discover_tests 的 CMake/Ctest 的谷歌测试

c++ - 如何在没有任何缓冲区的情况下将 stderr 重定向到文件?

c++ - 将二进制转换为负整数