即使在宏替换后也无法解析变量

时间:2019-09-11 14:21:43

标签: c++ googletest

我正在尝试学习gtest。我有要测试的课程Calculator

#pragma  once

// whattotest.cpp
#include <math.h>

class Calculator{
public:
    double squareRoot(const double a) {
        double b = sqrt(a);
        if(b != b) { // nan check
            return -1.0;
        }else{
            return sqrt(a);
        }
    }

    double add (const double a, const double b){
        return (a + b);
    }

    double multiply(const double a, const double b){
        return (a * b);
    }
};

我下面有测试类代码。

#include "gtest_example.hpp"
#include <gtest/gtest.h>

using namespace std;


class CalculatorTest : public ::testing::Test {

protected:
    virtual void SetUp() {
        calc = new Calculator();
    }
    virtual void TearDown() {
        delete calc;
    }
    Calculator *calc;
};

TEST(CalculatorTest, ShouldReturnSum) {

    SetUp();
    ASSERT_EQ(72, calc->add(36.0, 36.0));
}

TEST(CalculatorTest, ShouldReturnProduct) {
    SetUp();
    ASSERT_EQ(36, calc.multiply(6.0, 6.0));
}


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

在这两行ASSERT_EQ中,我都遇到以下错误。

Even after macro substitution can't resolve the variable calc.

我在做什么错嘻嘻。

1 个答案:

答案 0 :(得分:1)

使用固定装置时,应使用宏TEST_F而不是TEST

class CalculatorTest : public ::testing::Test {
    Calculator calc;
};

TEST_F(CalculatorTest, ShouldReturnSum)
{
    ASSERT_EQ(72, calc.add(36.0, 36.0));
}

TEST_F(CalculatorTest, ShouldReturnProduct)
{
    ASSERT_EQ(36, calc.multiply(6.0, 6.0));
}

没有固定装置,您可以简单地做:

TEST(CalculatorTest, ShouldReturnSum)
{
    Calculator calc;
    ASSERT_EQ(72, calc.add(36.0, 36.0));
}

TEST(CalculatorTest, ShouldReturnProduct)
{
    Calculator calc;
    ASSERT_EQ(36, calc.multiply(6.0, 6.0));
}