Link to home
Start Free TrialLog in
Avatar of gp
gpFlag for United States of America

asked on

Catch block code coverage by unit test

Hi,


Trying to write unit test to below method.


I am not able to go to catch block flow to get proper code coverage.


How to modify code to trigger catch block and assert something on this.


Please advise.


public static CartData parseCartMessage(CartSt cartStRecord) {
        CartDat cartData = null;
        try {
            if (cartStRecord != null) {
                Serial serialUnit = cartStRecord.getSerial();
                if (serialUnit != null) {
                    cartData = getCartData(serialUnit);
                }
            }
        } catch (Exception e) {
            log.error("Error parsing cart message",e);
        }
        return CartData;
    }

Open in new window


Avatar of Jeffrey Dake
Jeffrey Dake
Flag of United States of America image

One option would be to in your unit test the CartSt object that you create you could create a test class that extends CartSt. Then you could implement the getSerial method to throw a RuntimeException as its implementation. Then you will get into the Exception block in your method and you can test it logs as expected. 

ASKER CERTIFIED SOLUTION
Avatar of Jeffrey Dake
Jeffrey Dake
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gp

ASKER

CartSt object consist of that Serial object. Do I need to mock Serial object as well?
I keep getting null pointer exception from below call whether i do mock on Serial object or i just create Serial object using new keyword

cartStRecord.getSerial();
I always confuse when to use mock or when to use new keyword to create new object?
Please advise

If you are trying to test something besides the Exception, to get into your catch clause, then you would need to mock up what you want the getSerial() method to return.  You can return another mocked object (if you are trying to return a fake object, or you could return a real object, whatever makes more sense for your test.


Serial serial = mock(Serial.class);
doReturn(serial).when(cartSt).getSerial();

Open in new window

When you use a mocked object you just have to imagine that all the methods within that object are just stubs and essential will return nothing.  You have to tell the mocked object what you want it to return.  I was using a mocked object in your example of trying to get into the Exception clause, because it is an easy way to override the method to throw an Exception, that you may not get with other data.