I am trying to learn gtest. I have my class Calculator
that I want to test.
#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);
}
};
I have the test class code below.
#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();
}
In both the ASSERT_EQ
lines I get the following errors.
Even after macro substitution can't resolve the variable calc.
What am I doing wrong hee.
As you use fixture, you should use macro TEST_F
instead of 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));
}
Without fixture, you might simply do:
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));
}