【问题标题】:Why are C++ unit tests failing with die program为什么 C++ 单元测试在程序中失败
【发布时间】: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


【解决方案1】:

您遇到了未定义的行为。在初始化之前读取一个值是不合法的。

你的测试显示了一些有趣的东西:如果你还没有掷骰子,它的价值应该是多少?

也许你应该有一个零值,或者也许应该在构建时掷骰子。

【讨论】:

  • 编写“在构建时掷骰子”的代码看起来如何?设置“int roll_value = 1;”在 die.h 文件的 Class Die 构造函数中确实允许我的测试通过。但是,在构造时获得第一个“掷骰”以掷骰子的随机结果会更好吗? @guillaume
  • 该程序似乎仍然生成 int roll_value = 1 的随机结果;在 Class Die 构造函数中。所以我认为不会有问题
  • @Erin 是的,但第一个结果绝不是随机的。构造函数看起来像这样:Die() { roll(); } 甚至更好,创建一个返回新随机数的函数,并将其用于初始化第一个值和掷骰子。
猜你喜欢
  • 2022-06-29
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 2015-01-27
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多