在谷歌测试夹具中使用参考而不是指针?

时间:2014-03-06 16:49:04

标签: c++ testing googletest

以下是代码:

#include <gtest/gtest.h>

double sq(const double x) {
    return x*x;
}


class Sqtest : public ::testing::Test {
    protected:
        virtual void SetUp() {
            a = new int(1);
            b = new int(2);
            c = new int(3);
        }
        virtual void TearDown() {
            delete a;
            delete b;
            delete c;
        }
        int *a, *b, *c;
};

TEST_F (Sqtest, posnos) {
    EXPECT_EQ(1, sq(*a));
    EXPECT_EQ(4, sq(*b));
    EXPECT_EQ(9, sq(*c));
}

这一切都很好,但是如果在函数Sq中我使用引用,即

double sq(const double& x) {
    return x*x;
}

我应该如何相应地修改夹具?

1 个答案:

答案 0 :(得分:3)

对于这个特定的例子,没有必要使用指针。让Sqtest成员的类型为int,您就完成了:

#include <gtest/gtest.h>

int sq(int x)
{
    return x * x;
}


class Sqtest : public ::testing::Test
{
protected:
    virtual void SetUp() override
    {
        a = 1;
        b = 2;
        c = 3;
    }

    int a, b, c;
};

TEST_F(Sqtest, posnos)
{
    EXPECT_EQ(1, sq(a));
    EXPECT_EQ(4, sq(b));
    EXPECT_EQ(9, sq(c));
}