我正在使用 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 个参数的函数

为什么这不起作用?

最佳答案

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

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

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

关于c++ - 如何正确调用 Assert::ExpectException?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54268091/

10-10 19:40