How to call the Assert::ExpectException correctly?
Asked Answered
C

2

7

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?

Compatriot answered 19/1, 2019 at 14:28 Comment(4)
"Why isn't that working?" How exactly isn't it working?Gasify
Oh Sry, you are Right, forgot to write that information to the post. Wait, I’ll edit it!Compatriot
really no one who can help?Compatriot
Just be patient.Gasify
L
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);
}
Laliberte answered 23/3, 2019 at 21:11 Comment(2)
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.Idell
@MSalters: That is not true. At least at the time of this comment, there is an overload which takes any parameterless functorFlex
C
1

Or simply

Assert::ExpectException<std::invalid_argument>([]() {
    foo();
    });
Cenotaph answered 31/3, 2022 at 10:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.