【发布时间】:2020-12-09 15:20:54
【问题描述】:
我编写了以下程序: 死.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;
}
输出如下:
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
我正在使用以下测试进行测试:
TEST_CASE("Test that die returns a value between 1 and 6") {
Die die;
REQUIRE(die.rolled_value() > 0);
REQUIRE(die.rolled_value() < 7);
}
并且得到这个测试失败并显示以下消息:
REQUIRE( die.rolled_value() < 7 )
with expansion:
11860256 (0xb4f920) < 7
===============================================================================
test cases: 2 | 1 passed | 1 failed
assertions: 3 | 2 passed | 1 failed
我在运行这个程序时从来没有得到大于 7 的数字,但是测试,输出大于 7 的测试失败了……为什么会这样?
【问题讨论】:
-
只调用一次
srand(time(0));,而不是每次抽奖。 -
你在掷骰子前询问掷出的数字
-
通过测试判断,你应该在构造函数中设置滚动值,而不是单独调用成员函数。
-
好的,所以在Class Die构造函数中,roll_value应该是:int roll_value = 0;而不是 int roll_value;我理解正确吗? @molbdnilo
-
不在构造函数中,没有。您还没有任何构造函数。在您最喜欢的 C++ 书籍中了解它们。
标签: c++ unit-testing