Why I can't catch custom exception in test classes? If code throw custom exception, test immediatly fail.
System exceptions can be catched and handled in test methods without problems.
public class CustomException extends Exception {
}
This exception have 30 level API
public class MyClass {
public void methodToTest() {
// do something
someMethod();
}
@Future(callout = true)
private static void someMethod() {
try {
...
httpClient.send(httpRequest);
...
} catch (CustomException ex) {
throw ex;
} catch (Exception ex) {
// some actions
throw new CustomException('<message>', ex);
}
}
}
This class also have 30 level API
In test class I have 2 mocks (for HttpCallout)
First throw my Custom Exception and second throw CalloutException
In first case test immediatly stop and fail on line
httpClient.send(httpRequest);
In second case on line
throw new CustomException('<message>', ex);
UPD. code:
public class MyClasss {
public class CustomException extends Exception {
}
public void sendMethod() {
String endPoint = 'endPoint';
String body = 'body';
send(endPoint, body);
}
@Future(callout=true)
private static void send(String endPoint, String body) {
try {
HttpRequest request = new HttpRequest();
request.setEndpoint('https://' + endPoint + '/');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
request.setHeader('Content-Length', String.valueOf(Blob.valueOf(body).size()));
request.setHeader('Accept', 'application/json');
request.setBody(body);
request.setTimeout(120000);
new Http().send(request);
System.assert(false);
} catch (CustomException e) {
throw e;
System.assertEquals('error', e.getMessage());
} catch (Exception e) {
throw new CustomException('test', e);
}
}
}
And test class
@IsTest
private class MyTest {
private class Mock implements HttpCalloutMock {
Boolean wasCalled = false;
public HTTPResponse respond(HTTPRequest request) {
wasCalled = true;
throw new MyClasss.CustomException('error');
}
}
@IsTest
static void test() {
Mock m = new Mock();
Test.setMock(HttpCalloutMock.class, m);
MyClasss instance = new MyClasss();
Test.startTest();
instance.sendMethod();
Test.stopTest();
System.assert(m.wasCalled);
}
}