My Apex Class where I'm having a validation rule for duplicate name check in Catch block
public pagereference save(){
try{
upsert complexity;
pg = new ApexPages.StandardController(complexity).view();
pg.setredirect(true);
}catch(exception ex){
if(ex.getmessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION')){
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()));
}else{
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);
hpc.Save();
}catch(DMLException e) {
system.debug('all ok'+e);
system.assertEquals(e.getMessage(), e.getMessage());
}
}
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
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.insert pc1
, as it would then try to upsert from the controller's save method.