[SalesForce] Test a catch block for callout exception

I want to create a callout exception in test class for covering batch apex callout.
I am able to cover the try block but can't get, how to cover the catch block.
Can i hardcode or put something like this CalloutException excpObj with some particular exception so that the control enters the catch block??

for (Contact cont : scope){
    try {
         XXXXXXXX
    } catch (CalloutException excpObj) {
         some_method_name(cont.Id,' Callout Exception','---- ERROR = ' + excpObj.getMessage(),cont);
    }
}

Best Answer

There is exactly one way to do this.

Scaffold a System.CalloutException in your mock:

@TestVisible class UnauthorizedEndpointResponse implements HttpCalloutMock {
    public HttpResponse respond(HttpRequest request) {
        CalloutException e = (CalloutException)CalloutException.class.newInstance();
        e.setMessage('Unauthorized endpoint, please check Setup->Security->Remote site settings.');
        throw e;
    }
}

Then cause it to appear in your test with the normal HTTP mocks:

Test.setMock(HttpCalloutMock.class, new UnauthorizedEndpointResponse());
BatchClass.doTheCallout();
Related Topic