I am trying to write a test class for the Apex Class with try - catch block and this is my first time coding test classes. The Apex Class is like below which has trycatch
public class updateCaseRecord {
@AuraEnabled
public static void updateCheck(String caseId){
String msg = '';
try
{
List<Case> records = [select id,Status from Case WHERE Id = :caseId];
for (Case record : records)
{
record.Status = 'Closed';
}
update records;
}
catch(DmlException e)
{
for (Integer i = 0; i < e.getNumDml(); i++) {
msg =+ e.getDmlMessage(i) + '\n' ;
System.debug('getDmlFieldNames=' + e.getDmlFieldNames(i));
System.debug('getDmlMessage=' + e.getDmlMessage(i));
}
throw new AuraHandledException(msg);
}
catch(Exception e)
{
throw new AuraHandledException(e.getMessage());
}
finally { }
}}
And I wrote my test class like
@IsTest
public class updateCaseRecordTest {
@IsTest static void testIsUpdateCheck() {
ID parentRecType = '012U0000000PqA9IAK';
ID csRecType = '012U0000000QGv4IAG';
Account pa = new Account(Name='Test Parent Account', recordTypeId=parentRecType);
insert pa;
Account testAccount = new Account(Name='test', Industry='Biotech',Territory__c='EUR',BillingCity='Test',BillingCountry='Germany',ParentId=pa.id);
insert testAccount;
Contact c = new Contact(LastName='Test',LeadSource='Customer Service',AccountId=testAccount.Id);
insert c;
Case newCase1 = new Case();
newCase1.Subject = 'testStatusClosed';
newCase1.Status = 'New';
newCase1.Category__c = 'Inquiry';
newCase1.Sub_Category__c = 'Other';
newCase1.AccountId = testAccount.Id;
newCase1.ContactId = c.id;
newCase1.recordTypeId=csRecType;
insert newCase1;
Test.startTest();
try
{
updateCaseRecord.updateCheck(newCase1.Id);
List<Case> lCases = [SELECT Id,Status,OwnerId FROM Case WHERE Id =: newCase1.Id];
System.assertEquals('Closed', lCases[0].Status);
System.assertEquals(UserInfo.getUserId(), lCases[0].OwnerId);
}
catch(DMLException e) {
System.assertEquals(e.getMessage(), e.getMessage());
}
Test.stopTest();
}}
I thought I captured the try catch but when I run the test class it has only 57% code coverage and shows like below
Following one of the answers here
DmlException
in your test is incorrect. The code you're testing catches theDmlException
and then throws anAuraHandledException
.AuraHandledException
is what you'd want to catch in your test, then. – Derek F Apr 13 '20 at 15:39