Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write test code for testing my exception handling code?

I'm writing unit test for legacy Java code. Now I'm encountering a problem. Below is the class A I want to write test code for.

class A {

    public A(){

    }

    public void doSomething()throws DBException {
        try{
            //some code that might throw JDBCConnectionException 
        }catch(JDBCConnectionException e){
            notifyJDBCConnection()
        }catch(Exception e){

        }
    }   

    private void notifyJDBCConnection(){
        //do notification stuff
    }
}

Now say if I need to test whether the method notifyJDBCConnection() has been executed when JDBCConnectionException is caught. What is the right way to approach this problem? Or should I just write a test for testing method notifyJDBCConnection is okay?

like image 522
kenshinji Avatar asked Jul 18 '26 02:07

kenshinji


1 Answers

I presume that notifyJDBCConnection will call some kind of notification framework, be it an email sender or otherwise. If you mock that component using a framework like Mockito, you can verify that the appropriate calls to said component have been made.

like image 99
Joe C Avatar answered Jul 20 '26 14:07

Joe C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!