5

我正在使用 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));              
}

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

C++/CX 中的函数指针

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

为什么这不起作用?

4

1 回答 1

6

您需要将要测试的代码包装在要由Assert::ExpectException函数调用的 lambda 表达式中。

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

TEST_METHOD(Foo_ThrowsException)
{
    auto func = [] { Foo(); };
    Assert::ExpectException<std::invalid_argument>(func);
}
于 2019-03-23T21:11:54.913 回答