My Apex Class where I'm having a validation rule for duplicate name check in Catch block

 public pagereference save(){      
            upsert complexity;
            pg = new ApexPages.StandardController(complexity).view();     
        }catch(exception ex){
                String[] errorMsg = ex.getMessage().split('FIELD_CUSTOM_VALIDATION_EXCEPTION,');
                String[] errorMsgOnly = errorMsg[1].split(':');
                apexPages.addMessage(new apexPages.Message(ApexPages.Severity.ERROR,+errorMsgOnly[0].trim()));             
                apexPages.addMessage(new apexPages.Message(ApexPages.Severity.ERROR,'An unexpected error occurred. Please contact the support group with the error message'+ex.getmessage()));
            return null; 
        return pg;

My Test Class to cover the catch block is something like this

static testMethod void productComplexity_Negative(){     
       ProductComplexity__c pc = new ProductComplexity__c(name='test',Market_Segment__c='Small',Product_Type__c='New');
       insert pc;

       try {
        ProductComplexity__c pc1 = new ProductComplexity__c(name='test',Market_Segment__c='Small',Product_Type__c='New');
           insert pc1;
           ApexPages.standardController sc = new Apexpages.StandardController(pc1);
       HBCProductComplexity hpc = new HBCProductComplexity(sc); 
}catch(DMLException e) {
        system.debug('all ok'+e);
        system.assertEquals(e.getMessage(), e.getMessage());

Code Covered

But still I'm unable to cover the catch block.Since I'm inserting pc1 with the same name getting validation error their itself and it is not covering anything in the method

  • Instead of this hack- ex.getmessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION') use DMLException to catch DML relation validation message. Probably you're not able to cover the else part in your class? you should also highlight lines of code not getting covered.
    – Raul
    Jan 23, 2018 at 8:39
  • Updated the question
    – Eagerin Sf
    Jan 23, 2018 at 8:54
  • you should add asserts to verify the expected result. Maybe the records are not getting created, also check the debug logs while running the test class.
    – Raul
    Jan 23, 2018 at 9:07
  • at 'insert pc1' validation rule is triggering and it is entering into catch block and hence the remaining code is not executing. How to overcome this
    – Eagerin Sf
    Jan 23, 2018 at 10:30
  • 1
    it should work if you remove the code insert pc1, as it would then try to upsert from the controller's save method.
    – Raul
    Jan 23, 2018 at 10:35

1 Answer 1


Instead of inserting the record in try block of test class, call save method hpc.Save(); as it would execute DML inside the main class with the upsert statement, thus covering the controller's catch.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .