C++回测问题: How to check if constructor has failed when it suppose to fail (given invalid arguments inputted)

标签 c++

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

我的日期构造函数:

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 date(记录了seed)来测试构造函数是否能够成功进行错误处理。由于输入是无效日期,因此每个测试都应该抛出一个期望值。因此,如果某些测试失败(意味着在给定无效日期输入的情况下不会抛出异常)打印出用于随机数生成器的随机种子,以便程序员可以重新使用相同的种子并重现错误。

我不知道该怎么做,我该如何检查是否抛出期望消息?什么应该进入 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? 

        }
    }
}

最佳答案

我最近遇到了一个 blog about testing at Google ,他们在其中链接了一个示例,说明他们如何 writetest代码。他们的一个案例看起来很像你可以在这里使用的东西(测试某些东西应该失败,并且正如其他评论提到的那样;抛出异常):

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

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

关于C++回测问题: How to check if constructor has failed when it suppose to fail (given invalid arguments inputted),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58425850/

相关文章:

c++ - 通过 CMake 将外部库包含到 CLion 项目中

c++ - 在模板模板参数中抛出多模板类 - 模板绑定(bind)?

c++ - 如何在 qt 标签中显示 em dash 字符?

c++ - 为什么使用字符串初始化的 C++ 位集会被反转?

c++ - OpenCV 中的自定义 SIFT 检测器

c++ - 通过网络广播服务器存在

c++ - 如何在main之外的函数中访问数组?

c++ - 不用调试工具的调试技巧

c++ - 将 Visual Studio 2008 与 C/C++ 结合使用

c++ - 三元运算符将类扩展宏应用于两个操作数