Gino Pensuni
Gino Pensuni

Reputation: 366

How to call the Assert::ExpectException correctly?

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?

Upvotes: 7

Views: 6425

Answers (2)

Mohamed Oulmahdi
Mohamed Oulmahdi

Reputation: 85

Or simply

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

Upvotes: 1

Chris Olsen
Chris Olsen

Reputation: 3511

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

Upvotes: 9

Related Questions