Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 872
Gino Pensuni Avatar asked Jan 19 '19 14:01

Gino Pensuni


People also ask

How do I use Assert to verify that an exception has been thrown?

You can use the try{act/fail}catch{assert} method, which can be useful for frameworks that don't have direct support for exception tests other than ExpectedException .

How do you assert exceptions in Python?

There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.

How to handle exception in PHPUnit?

You can also use a docblock annotation until PHPUnit 9 is released: class ExceptionTest extends PHPUnit_Framework_TestCase { /** * @expectedException InvalidArgumentException */ public function testException() { ... } } IMO, this is the preferred method.


1 Answers

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);
}
like image 59
Chris Olsen Avatar answered Nov 01 '22 09:11

Chris Olsen