unit test for catch block using kotlin mockito - unit-testing

try {
return Response.ok(payHandler.getFeesForPay(body, config)).build()
}
catch (e: Exception) {
return exceptionHelper.buildResponseFromException(e)
}
How to write unit test using mockito for code in catch block

Without a more detailed code, all we can suggest you is to mock payHandler to throw an exception as follows:
when(payHandler.getFeesForPay(any(), any()))
.thenThrow(NullPointerException.class);

Related

PHPUnit test code inside catch block

I have a Symfony controller using try...catch.
I use phpunit to test my application. I have searched but havent found a way how to test the code inside a catch exception. How can I force php unit to pretend that something went wrong and enters the catch block and test this as well?
ie:
try {
$foo = 1;
} catch (\Exception $ex) {
$mail = new Mail();
$mail->sendMail();
return new Response();
}
How can I tell phpunit to throw an \Exception so it will test code inside catch block of above?
Well, under those conditions, it will obviously not throw any exceptions, but consider the function your try/catch lies within. You need to unit test that function, and provide arguments that will cause it to fail, and catch.
For instance:
public function doStuff($argument) {
try {
$parsed = (int)$argument; //but what if $argument is a string with letters
} catch (\Exception $ex) {
//do stuff
}
To test that an exception is thrown when you mess it up:
public function testDoStuff() {
// get a mock of the class, let's just call it $mock
// do some regular asserts if you want
$this->setExpectedException('\Exception');
$mock->doStuff("haha, you can't parse this");
}
If you really have some complex stuff in your catch block you can move it to separate protected method of the controller and test it separately. You can easily access protected method outside of its class using reflection.

Why can I not catch my exception?

I have following function that catches the system-exception of a ComObject and throws my own exception off:
int TReader::ExecSQL(...) {
try {
// ...
} catch (Comobj::EOleException& e) {
throw myDBError("TReader::Open", "TReader", e.Message);
}
// ...
}
I can not catch my own exception, getting always "Exception unknown!"! Why?
void main() {
try {
ExecSQL(...);
} catch(myDBError& e) {
log(e.Message);
} catch(...) {
log("Exception unknown!");
}
}
Use catch(const myDBError& e) { instead.
An anonymous temporary cannot bind to a non-const reference, so a throw will not be intercepted at the current catch site.
If try-catch block generates not Comobj::EOleException, but something else, that may be problem.
Also check, maybe myDBError constructor generates another exception, with another type :-)
That would be funniest explanation, why you can't catch myDBError, but still catch something :-)

How should I use C++ constructor exceptions?

I've never tried using C++ exceptions until a few days ago, and I'm not sure if I'm doing this right. I'm trying to throw an exception on a constructor that fails, like
X::X() {
/*...*/
if(error)
throw;
/*...*/
}
And using it like:
try {
X a;
X b;
X c;
}
catch (...) {
// error handling
}
The debugger (VS) says there's an unhanded exception on the throw. Code after throw gets executed (I though throw worked like return), and the catch block isn't executed. What am I missing here?
I may have oversimplified this post a little bit, but the original code is a bit complex to post here.
It's because you do not throw an exception object. You should use throw like this:
throw std::runtime_error("Error message");
then you'll be able to catch it via
try {
...
} catch (const std::runtime_error& e) {
/* Handling */
}
Have a look at the stdexcept header.
You should throw some exception (generally an instance of some subclass of std::exception), e.g.
X::X() {
/*...*/
if(error)
throw std::runtime_error("my bad");
/*...*/
}
See std::runtime_error for more.
throw; without any exception makes only sense inside a catch block.
I agree with Danvil's answer: throwing an exception inside a constructor is poor taste.

Will exception thrown in catch block be caught by later catch blocks?

Consider the following C++ code:
try {
throw foo(1);
} catch (foo &err) {
throw bar(2);
} catch (bar &err) {
// Will throw of bar(2) be caught here?
}
I would expect the answer is no since it is not inside the try block and I see in another question the answer is no for Java, but want to confirm C++ is also no. Yes, I can run a test program, but I'd like to know the language definition of the behavior in the remote case that my compiler has a bug.
No. Only exceptions thrown in the associated try block may be caught by a catch block.
No, It won't, An enclosing catch block upwards the hierarchy will be able to catch it.
Sample Example:
void doSomething()
{
try
{
throw foo(1);
}
catch (foo &err)
{
throw bar(2);
}
catch (bar &err)
{
// Will throw of bar(2) be caught here?
// NO It cannot & wont
}
}
int main()
{
try
{
doSomething();
}
catch(...)
{
//Catches the throw from catch handler in doSomething()
}
return 0;
}
No, a catch block handles the nearest exception, so if you try ... catch ( Exception &exc ) ... catch ( SomethingDerived &derivedExc ) the exception will be handled in the &exc block
You might achieve the desired behaviour by exception delegation to the calling method

Unit Testing an Unhandled Exception Handler with NUnit

I have a unit test that deliberately generates an unhandled exception. I've wired up a handler for unhandled exceptions (which I'd like to test) using:
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
My test is as follows:
LogClient client = new LogClient(); // The handler is wired up in here
Trace.TraceInformation( "About to cause an unhandled divide-by-zero exception." );
for ( int i = 10; i > -10; --i )
{
int j = 100 / i;
Console.WriteLine( "i={0}, j={1}", i, j );
}
Assert.NotNull( client.UnhandledException );
Of course, the exception is thrown and NUnit catches it and fails the test. I've tried adding the
[ExpectedException(typeof(DivideByZeroException))]
and the test "passes" but my handler is never called and the Assert.NotNull is never executed. I'm wondering if it is possible to write a unit test for an unhandled exception handler. Any pointers appreciated.
I'm using NUnit 2.5.7 w/ VS 2010.
You are not testing the handler, but the condition in which the handler should act. Concider extracting the Exceptionhandler into its own class like:
internal class AnExceptionHandler
{
public static void UnhandledHandler(object sender, UnhandledExceptionEventArgs args)
{
//Do your thing and test this.
}
}
Instantiate this class, and hook up the event up to this.
Hope this helps.
Regards,
Morten