Why are C++ unit tests failing with die program

Viewed 85

I have the following program written: die.h

class Die {
    public:
        // Randomly assigns a value to roll_value in the range of 1 to 6
        void roll();
        // Returns roll_value
        int rolled_value() const;
    private:
        // Stores a randomly assigned value
        int roll_value;
        // Die sides, initialized to 6
        int sides = 6;
};

die.cpp

#include "die.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

void Die::roll() {
   srand(time(0));
   roll_value = rand()%sides + 1;
}
int Die::rolled_value() const {
   return roll_value;
}

main.cpp

#include "die.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include<windows.h>

using std::cout;

int main() {
  
   srand(time(0));
   Die die;
   int i = 0;
   for(i=1; i<=10; i++)
   {
       die.roll();
      Sleep(1000);
       cout << "Roll #"<< i << ", Roll Value: " << die.rolled_value() << "\n";
   }
   return 0;
}

Which outputs the following:

Roll #1, Roll Value: 4
Roll #2, Roll Value: 1
Roll #3, Roll Value: 4
Roll #4, Roll Value: 2
Roll #5, Roll Value: 5
Roll #6, Roll Value: 2
Roll #7, Roll Value: 5
Roll #8, Roll Value: 3
Roll #9, Roll Value: 6
Roll #10, Roll Value: 3

I'm testing with the following test:

TEST_CASE("Test that die returns a value between 1 and 6") {
    Die die;
    REQUIRE(die.rolled_value() > 0);
    REQUIRE(die.rolled_value() < 7);
}

And getting that this test is failing with the following message:

  REQUIRE( die.rolled_value() < 7 )
with expansion:
  11860256 (0xb4f920) < 7

===============================================================================
test cases: 2 | 1 passed | 1 failed
assertions: 3 | 2 passed | 1 failed

I never have gotten a number greater than 7 when running this program but the test, testing for output greater than 7 is failing... Why is this happening?

1 Answers

You're experiencing undefined behavior. It is not legal to read a value before it's initialized.

Your test is showing something interesting: What should be the value of a die when you haven't rolled it yet?

Maybe you should have a zero value, or maybe the die should be rolled when constructed.

Related