How to call the Assert::ExpectException correctly?

5.8k Views Asked by At

I'm writing some unit tests using Microsoft's CppUnitTestFramework.

I want to test, if the method I call throws the correct exception. My code is:

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));              
}

In the link below I wrote the call similar to the last answer:

Function Pointers in C++/CX

When compiling it, I get the C2064 Error: term does not evaluate to a function taking 0 arguments

Why isn't that working?

2

There are 2 best solutions below

2
On BEST ANSWER

You need to wrap the code under test in a lambda expression to be called by the Assert::ExpectException function.

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

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

Or simply

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