I have A Given Sample Apex Code

    global static String doGet(){
        RestRequest req  = RestContext.request;
        RestResponse res = RestContext.response;
            String UserId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
            if(UserId =='' || UserId ==null) UserId = userinfo.getUserId();
            return getProfileDetails(UserId);    
        }catch(Exception e){
            throw new CustomException(PG_Utils.getException(GENERIC_ERROR,GENERIC_ERROR_TYPE, CustomException__c.getValues('GEN0001').Error_Description__c));

The Above Code Represents In Post Man if you give portal User Id or Not Given any Id,It will Get the Particular Profile Details of User For that I have Wrote Test Class Like:

RestRequest req = new RestRequest(); 
 req.httpMethod = 'GET';
 RestContext.request = req;

I am unable to cover the Try Catch Block in Test Class,How to Cover Apex Class Try Catch Block in Test Class,Try Catch Block represents if any Wrong User Id is Given in postMan,it Should have Throw Error Message in PostMna,Please anayone Guide Me how to Cover Try Catch Block in Test Class

1 Answer 1


You have to make another call with an erroneous Id. Something like:

RestRequest okReq = new RestRequest(); 
okReq.httpMethod = 'GET';
RestContext.request = okReq;

String wrongId = 'this is not an ID';

//since the method trows an exception, you need to try/catch it
    RestRequest worngReq = new RestRequest(); 
    wronReq.httpMethod = 'GET';
    RestContext.request = wrongReq;
}catch(Exception e){
    System.AssertEquals(e.getMessage(), PG_Utils.getException(GENERIC_ERROR,GENERIC_ERROR_TYPE, CustomException__c.getValues('GEN0001').Error_Description__c));
  • what is e.getmessage()? what does it contain? how it will be equal to PG_Utils.getException(GENERIC_ERROR,GENERIC_ERROR_TYPE, CustomException__c.getValues('GEN0001').Error_Description__c
    – user30475
    Commented Apr 28, 2016 at 10:58
  • cananyone explain to me?
    – user30475
    Commented Apr 28, 2016 at 10:58
  • When you catch an exception (in this case it's called "e") you can access lots of info. One of it is the message generated on the error. When you throw a new exception, you choose which message to display. In your case: throw new CustomException(--message--); Commented Apr 28, 2016 at 14:13
  • That simply asserts that the message you throw is the message you catch. =D Commented Apr 28, 2016 at 14:18

You must log in to answer this question.