首页 > 解决方案 > c ++回测问题:当构造函数失败时如何检查它是否失败(给定输入的参数无效)

问题描述

首先要强调的是,我的问题不是关于构造函数中的错误处理。所以我正在做这个作业来编写一个Date类,首先是关于构造函数,当然它必须能够处理无效的日期输入,我已经实现了我的构造函数,如下所示,错误处理部分使用实现试着抓:

我的日期构造函数:

Date(unsigned y, unsigned m, unsigned d)
{
try {
    check_valid(y, m, d);
    my_year = y; my_month = m; my_day = d; 
    }
catch (const std::exception& msg) {
        std::cerr << msg.what() << std::endl;
    }
}

check_valid 函数:

void Date::check_valid(unsigned y, unsigned m, unsigned d)
{
    MYASSERT(y >= 1900 && y <2200, "The year is invalid");
    MYASSERT(m >= 1 && m <= 12, "The year is invalid");
    MYASSERT(d >= 1 && d <= dmax, "The year is invalid"); //dmax is just no. of days in the month
}

#define MYASSERT(cond, msg) \
{ \
    if (!(cond)) \
    { \
        throw std::invalid_argument(msg); \
    } \
}

问题: 我被要求写一个回测程序:随机生成大量的INVALID日期(带有种子记录)来测试构造函数是否能够成功执行错误处理。由于输入的日期无效,因此每个测试都应该抛出一个期望。因此,如果某些测试失败(意味着在输入无效日期的情况下不会引发异常)打印出用于随机数生成器的随机种子,以便程序员可以重新使用相同的种子并重现错误。

我不知道该怎么做,我如何检查是否抛出了期望消息?if 语句应该包含什么内容?

while (counter < 1000) {
    seed = rand();
    srand(seed);

    unsigned y = rand() % 500 + 1800;   //rand year between (1800, 2299)
    unsigned m = rand() % 20;           //rand month between (0, 19)
    unsigned d = rand() % 40;           //rand day between (0, 39)

    if (! isValidDate(y, m, d))  //some function to filter out the valid date
    { 
        counter++;
        Date somedate(y, m, d);  //use the constructor
        { 

        // the constructor is used above, but i have no idea if an expectation is thrown or not 
        // if an expectation is thrown, then print seed, how do i write this code? 

        }
    }
}

标签: c++

解决方案


我最近看到了一篇关于 Google 测试的博客,其中链接了一个关于他们如何编写测试代码的示例。他们的一个案例看起来非常像你可以在这里使用的东西(测试某些东西应该失败,并且正如其他评论所提到的;抛出异常):

  public void testStart_whileRunning() {
    stopwatch.start();
    try {
      stopwatch.start();
      fail();
    } catch (IllegalStateException expected) {
    }
    assertTrue(stopwatch.isRunning());
  }

该示例在 Java 中,但在 C++ 中的原理相同:有一个fail()方法在运行时无条件地使测试失败,但如果您的代码“正确失败”则跳过该方法。


推荐阅读