function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ShreyankaShreyanka 

Test class for "Case comments should be required on Case approval or rejection"

Hi Everyone,

For below apex code i have written test class but the code coverage is 70%, couldn't able to increase the coverage. 
And test class is failing, giving below errors:
User-added image

Please anyone help me in increasing the coverage of test class and resolving the above errors.

Thanks in advance!
public with sharing class CaseCommentsHandler {
    public static void checkApprovalRejectionComments(Map<Id,Case> newCaseMap, Map<Id,Case> oldCaseMap) 
    {
        Set<Id> caseIds = new Set<Id>();
        Set<String> cSubtypes = new Set<string>();
        
        for(Case_comment__mdt subtype: [Select Case_Subtype__c From Case_comment__mdt]){
            cSubtypes.add(subtype.Case_Subtype__c);
        }
         
        for(Case updatedCase : newCaseMap.values()) {
            if(cSubtypes.contains(updatedCase.Case_Subtype__c))  {
                if((oldCaseMap.get(updatedCase.Id).Approval_Status__c != updatedCase.Approval_Status__c) &&
                   (updatedCase.Approval_Status__c == 'Approved' || updatedCase.Approval_Status__c == 'Rejected'))
                {
                    caseIds.add(updatedCase.Id);
                }
            }
        }
        
        Set<Id> processInstanceIds = new Set<Id>();
        if(!caseIds.isEmpty()) {
            for(Case updatedCase : [SELECT (SELECT Id FROM ProcessInstances ORDER BY CreatedDate DESC LIMIT 1)
                                    FROM Case WHERE Id IN : caseIds]) {
                                         if (!updatedCase.ProcessInstances.isEmpty()) {
    								processInstanceIds.add(updatedCase.ProcessInstances[0].Id);
									}
                                    }
            
            for(ProcessInstance pi : [SELECT TargetObjectId, (SELECT Id, StepStatus, Comments FROM Steps WHERE StepStatus IN ('Approved', 'Rejected')
                                     ORDER BY CreatedDate DESC LIMIT 2) FROM ProcessInstance WHERE Id IN :processInstanceIds ORDER BY CreatedDate DESC]){
											if (pi.Steps.size() == 1) {
                                              if ((pi.Steps[0].Comments == null || pi.Steps[0].Comments.trim().length() == 0) &&
                                                  (pi.Steps[0].StepStatus == 'Rejected')) {
                                                      newCaseMap.get(pi.TargetObjectId).addError('Please provide rejection comments when rejecting the case!');
                                                  }
                                             else if (pi.Steps[0].StepStatus == 'Approved' && (pi.Steps[0].Comments == null || pi.Steps[0].Comments.trim().length() == 0)) {
                                                  newCaseMap.get(pi.TargetObjectId).addError('Please provide approval comments when approving the case!');
                                              }
                                          }
                                      }
        }
    }
}
 
@isTest
private class CaseCommentsTest{
     @isTest
     static void testCommentRequiredOnApproval() {
        //try {
        // Create a test case record
        Case c1 = new Case();
        c1.Subject = 'Test Case 1';
        c1.Case_Subtype__c = 'Capital Loan';
        c1.Approval_Status__c = 'Submitted';
        c1.Type = 'Loans';
        c1.Case_Type__c = 'Transaction';
        insert c1;

        Test.startTest();
         c1.Approval_Status__c='Approved';
         c1.addError('Please provide approval comments when approving the case!');
         try{
        	update c1;
            System.assert(false, 'Expected validation error');
        }catch(DmlException e){
			 String expectedError = 'Please provide approval comments when approving the case!';
            System.assert(e.getMessage().contains('expectedError'),'Expected validation error:' +expectedError);
        }
         
        Test.stopTest();
         
        Case updatedCase = [Select Id From Case Where Id= :c1.Id];
         
        System.assert(updatedCase.hasErrors(),'Expected validation error');
}

@IsTest
static void testCommentRequiredOnRejection() {
    //try {
        // Create a test case record
        Case c2 = new Case();
        c2.Subject = 'Test Case 1';
        c2.Case_Subtype__c = 'Capital Loan';
        c2.Approval_Status__c = 'Submitted';
        c2.Type = 'Loans';
        c2.Case_Type__c = 'Transaction';

        insert c2;
    
        Test.startTest();
        c2.Approval_Status__c='Rejected';
        c2.addError('Please provide rejection comments when rejecting the case!');
    	try{
        	update c2;
            System.assert(false, 'Expected validation error');
        }catch(DmlException e){
            String expectedError = 'Please provide rejection comments when rejecting the case!';
            System.assert(e.getMessage().contains('expectedError'),'Expected validation error:' +expectedError);
        }
        Test.stopTest();
         
       Case updatedCase = [Select Id From Case Where Id= :c2.Id];
         
       System.assert(updatedCase.hasErrors(),'Expected validation error');
}
}

 
SubratSubrat (Salesforce Developers) 
Hello Shreyanka ,

Can you try with the below test class :
@isTest
private class CaseCommentsTest {
    @isTest
    static void testCommentRequiredOnApproval() {
        Case c1 = new Case();
        c1.Subject = 'Test Case 1';
        c1.Case_Subtype__c = 'Capital Loan';
        c1.Approval_Status__c = 'Submitted';
        c1.Type = 'Loans';
        c1.Case_Type__c = 'Transaction';
        insert c1;

        Test.startTest();
        c1.Approval_Status__c = 'Approved';
        c1.addError('Please provide approval comments when approving the case!');
        try {
            update c1;
            System.assert(false, 'Expected validation error');
        } catch (DmlException e) {
            String expectedError = 'Please provide approval comments when approving the case!';
            System.assert(e.getMessage().contains(expectedError), 'Expected validation error: ' + expectedError);
        }

        Test.stopTest();

        Case updatedCase = [SELECT Id FROM Case WHERE Id = :c1.Id];

        System.assert(updatedCase.hasErrors(), 'Expected validation error');
    }

    @IsTest
    static void testCommentRequiredOnRejection() {
        Case c2 = new Case();
        c2.Subject = 'Test Case 2';
        c2.Case_Subtype__c = 'Capital Loan';
        c2.Approval_Status__c = 'Submitted';
        c2.Type = 'Loans';
        c2.Case_Type__c = 'Transaction';

        insert c2;

        Test.startTest();
        c2.Approval_Status__c = 'Rejected';
        c2.addError('Please provide rejection comments when rejecting the case!');
        try {
            update c2;
            System.assert(false, 'Expected validation error');
        } catch (DmlException e) {
            String expectedError = 'Please provide rejection comments when rejecting the case!';
            System.assert(e.getMessage().contains(expectedError), 'Expected validation error: ' + expectedError);
        }
        Test.stopTest();

        Case updatedCase = [SELECT Id FROM Case WHERE Id = :c2.Id];

        System.assert(updatedCase.hasErrors(), 'Expected validation error');
    }

    @IsTest
    static void testNoCommentRequiredOnNonSubtypeCase() {
        Case c3 = new Case();
        c3.Subject = 'Test Case 3';
        c3.Case_Subtype__c = 'Non-Subtype';
        c3.Approval_Status__c = 'Submitted';
        c3.Type = 'Loans';
        c3.Case_Type__c = 'Transaction';

        insert c3;

        Test.startTest();
        c3.Approval_Status__c = 'Approved';
        update c3;
        Test.stopTest();

        Case updatedCase = [SELECT Id FROM Case WHERE Id = :c3.Id];

        System.assert(!updatedCase.hasErrors(), 'No validation error should occur');
    }

    @IsTest
    static void testNoCommentRequiredOnNonApprovalRejectionStatus() {
        Case c4 = new Case();
        c4.Subject = 'Test Case 4';
        c4.Case_Subtype__c = 'Capital Loan';
        c4.Approval_Status__c = 'Submitted';
        c4.Type = 'Loans';
        c4.Case_Type__c = 'Transaction';

        insert c4;

        Test.startTest();
        c4.Approval_Status__c = 'In Progress';
        update c4;
        Test.stopTest();

        Case updatedCase = [SELECT Id FROM Case WHERE Id = :c4.Id];

        System.assert(!updatedCase.hasErrors(), 'No validation error should occur');
    }
}

Hope this helps !
Thank you.