I have tested the .decreaseInventory() manually in my main file so I know it works correctly but when I run a google test on it, it fails and gives me an error. How could I fix this?
Player class:
#ifndef PLAYER_H
#define PLAYER_H
#include <iostream>
using namespace std;
class Player
{
int inventory;
public:
Player();
int decreaseInventory(int numOfBeers);
void setInventory(int newInventory);
int getBackOrder();
int getCost();
int getInventory();
bool operator ==(Player& p);
};
Player::Player()
{
cout << " Default Player Constructor\n";
inventory = 12;
backorder = 0;
cost = 0;
orderDelay = 0;
shipmentDeplay = 0;
}
void Player::setInventory(int newInventory)
{
inventory = newInventory;
}
int Player::decreaseInventory(int numOfBeers)
{
inventory = inventory - numOfBeers;
}
int Player::getInventory()
{
return inventory;
}
test.cpp:
#include "gtest/gtest.h"
#include "Player.h"
TEST(playerTest, decreaseInventoryTest ) {
Player p;
int curr_inv = p.getInventory();
EXPECT_EQ(curr_inv-3, p.decreaseInventory(3));
}
Error:
Running main() from gtest_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from playerTest
[ RUN ] playerTest.decreaseInventoryTest
Default Player Constructor
/home/hammad/se-02-team-21/tests.cpp:13: Failure
Expected: curr_inv-3
Which is: 9
To be equal to: p.decreaseInventory(3)
Which is: 1740894128
[ FAILED ] playerTest.decreaseInventoryTest (1 ms)
[----------] 1 test from playerTest (1 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] playerTest.decreaseInventoryTest
1 FAILED TEST
Why does it fail and give a garbage value? I am already using a default constructor and in general it works properly.
Your method is:
int Player::decreaseInventory(int numOfBeers) { inventory = inventory - numOfBeers; }
Your test is:
EXPECT_EQ(curr_inv-3, p.decreaseInventory(3));
The macro EXPECT_EQ
compares the value returned from p.decreaseInventory(3)
with curr_inv-3
. The method does not return anything.
Not returning something from a method that is declared to return something is undefined behavior. Your compiler should have warned you about it and your test was successful in the sense that you have a failing test that is caused by a real bug in your code that you now can fix.