6

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?

Gino Pensuni
  • 356
  • 4
  • 15

2 Answers2

9

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);
}
Chris Olsen
  • 3,243
  • 1
  • 27
  • 41
  • 1
    This works because the lambda is non-capturing, and therefore can be converted to a `void(*)(void)` function pointer. `Assert::ExpectException` needs a function pointer. – MSalters Aug 21 '20 at 12:02
  • @MSalters: That is not true. At least at the time of this comment, there is an overload which takes any parameterless functor – ArgusMagnus May 19 '21 at 12:23
1

Or simply

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