+ Start a Discussion
Scott.MScott.M 

Test exception handling with HttpCalloutMock

The new mock classes  are great! Except for one thing I have a block of code that does something like this

 

try {

 //do a callout

} catch(Exception ex) {

 //handle an expection 

}

 

I want to test the handling of an exception part of the code. Initially I though I could just create a mock class that throws an exception in the response method something like this

 

@isTest
public class MockHttpCalloutGenerator implements HttpCalloutMock {
 
public HTTPResponse respond(HTTPRequest req){
 
throw new CustomException('Exception occured during callout');
 
}
 
}

 

The problem is that when I run the test I get a System.UnexpectedException: Exception occured during callout. And it doesn't exercise my exception handling. Is there a way to do this, or am I hosed for testing callout exception handling?

 

Andrew CoxAndrew Cox
Dear Scott,
Can't see any responses to this but wondered if you found a solution. I too would like to be able to throw an exception to test callout exception handling!
Please let me know if you found  a way.
Thanks,

Andrew