【问题标题】:How to call the Assert::ExpectException correctly?如何正确调用 Assert::ExpectException?
【发布时间】:2019-06-13 13:14:32
【问题描述】:

我正在使用 Microsoft 的 CppUnitTestFramework 编写一些单元测试。

我想测试一下,我调用的方法是否抛出了正确的异常。我的代码是:

TEST_METHOD(test_for_correct_exception_by_input_with_whitespaces)
{
            std::string input{ "meet me at the corner" };
            Assert::ExpectException<std::invalid_argument>(AutokeyCipher::encrypt(input, primer));              
}

在下面的链接中,我写了类似于上一个答案的调用:

Function Pointers in C++/CX

编译时,我得到 C2064 错误:术语不计算为采用 0 个参数的函数

为什么这不起作用?

【问题讨论】:

  • “为什么这不起作用?”到底是怎么回事?
  • 哦,对不起,你是对的,忘记在帖子中写下该信息。等等,我来编辑!
  • 真的没有人可以帮忙吗?
  • 请耐心等待。

标签: c++ unit-testing exception assertion microsoft-cpp-unit-test


【解决方案1】:

您需要将被测代码封装在一个 lambda 表达式中,以供 Assert::ExpectException 函数调用。

void Foo()
{
    throw std::invalid_argument("test");
}

TEST_METHOD(Foo_ThrowsException)
{
    auto func = [] { Foo(); };
    Assert::ExpectException<std::invalid_argument>(func);
}

【讨论】:

  • 这是有效的,因为 lambda 是非捕获的,因此可以转换为 void(*)(void) 函数指针。 Assert::ExpectException 需要一个函数指针。
  • @MSalters:这不是真的。至少在发表此评论时,有一个重载可以接受任何无参数仿函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-01
  • 2011-07-18
  • 2020-08-25
  • 2013-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多