测试特定的异常类型被抛出,异常具有正确的属性 [英] Test a specific exception type is thrown AND the exception has the right properties

查看:161
本文介绍了测试特定的异常类型被抛出,异常具有正确的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试在某种情况下抛出 MyException EXPECT_THROW 在这里很好。但我也想检查异常有一个特定的状态例如 e.msg()==Cucumber overflow

I want to test that MyException is thrown in a certain case. EXPECT_THROW is good here. But I also want to check the exception has a specific state e.g e.msg() == "Cucumber overflow".

在GTest中最好如何实现?

How is this best implemented in GTest?

推荐答案

我大多是第二次Lilshieste的回答, $ b验证不会抛出错误的异常类型:

I mostly second Lilshieste's answer but would add that you also should verify that the wrong exception type is not thrown:

#include <stdexcept>
#include "gtest/gtest.h"

struct foo
{
    int bar(int i) {
        if (i > 100) {
            throw std::out_of_range("Out of range");
        }
        return i;
    }
};

TEST(foo_test,out_of_range)
{
    foo f;
    try {
        f.bar(111);
        FAIL() << "Expected std::out_of_range";
    }
    catch(std::out_of_range const & err) {
        EXPECT_EQ(err.what(),std::string("Out of range"));
    }
    catch(...) {
        FAIL() << "Expected std::out_of_range";
    }
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

这篇关于测试特定的异常类型被抛出,异常具有正确的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆