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?
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 .
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With