如何正确调用 Assert::ExpectException

How to call the Assert::ExpectException correctly?

本文关键字:ExpectException Assert 调用 何正确      更新时间:2023-10-16

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

为什么这不起作用?

您需要

将测试中的代码包装在 lambda 表达式中,以便由 Assert::ExpectException 函数调用。

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

或者干脆

Assert::ExpectException<std::invalid_argument>([]() {
    foo();
    });