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
Haseeb Ahmad 9Haseeb Ahmad 9 

Trigger Code coverage issue

Hi Everyone,

I need some help and guidance to increase code coverage for this trigger as I am not able to deeply this in production. 

Trigger on cases:
 
trigger CaseTrigger on Case(after insert, after update,before insert, before update) {
    
  Profile userProfile = [SELECT Id FROM Profile WHERE Name='Professional Services']; 
if(userProfile.Id != UserInfo.getProfileId()) 
return;
    
    switch on Trigger.operationType {
        when BEFORE_INSERT {
            CaseHelper.checkCaseAssignedRulesInsert(trigger.new);
        }
        when BEFORE_UPDATE{
            CaseHelper.checkCaseAssignedRulesInsert(trigger.new);
            CaseHelper.timestamp(trigger.new);
        }
        when AFTER_UPDATE {
            CaseHelper.checkCasePostUpdatesData(Trigger.oldMap, trigger.new);
        }
    }
}
Helper class:
global with sharing class CaseHelper {
    
    public static void checkCaseAssignedRulesInsert(List < Case > lstMap) {
        List<Id> mapOppCase = new List<Id>();

        for (Case unitCase: lstMap) {
            mapOppCase.add(unitCase.OppToCase__c);
        }

        Id caseRecordId = SobjectType.Case.getRecordTypeInfosByName().get('PS Only').getRecordTypeId();
List<Case> listCase = [SELECT Id,CaseNumber,Status From Case WHERE Status != 'Closed' AND OppToCase__c  in: mapOppCase and Id not in: lstMap and RecordTypeId =: caseRecordId ];
        for (Case unitCase: listCase) {
            AuraHandledException e = new AuraHandledException(null);
            e.setMessage('There is already a case assigned to this Opportunity,Case Number:' + unitCase.CaseNumber +'Only one case can be active at a time, please chatter @ProServ for additional requests.');
            throw e;
        }
    }
    
    public static void timestamp (List<Case> timestampcases){
        for (Case unitCase: timestampcases) {
            if(unitCase.Status == 'In Progress') unitCase.Time_Spent_in_New_Status__c = System.now();
            if(unitCase.Status == 'Additional Information Required') unitCase.Time_Spent_in_Progress__c = System.now();
            if(unitCase.Status == 'Waiting for Scoping Call') unitCase.Time_Spent_Additional_information_Requir__c = System.now();
            if(unitCase.Status == 'Closed') unitCase.Time_Spent_Waiting_for_Scoping_Call__c = System.now();
        }
    }

    public static void checkCasePostUpdatesData(Map < ID, Case > oldMap, List < Case > newMap) {
        Map < String, Schema.SObjectField > schemaFieldMap = Schema.SObjectType.Case.fields.getMap();
        List < ConnectApi.BatchInput > batchInputs = new List < ConnectApi.BatchInput > ();
        List < String > fieldToSkip = new List < String > {
             'Status'      
        };
   
        for (Case newCase: newMap) {
            system.debug('status'+newCase);
            String caseStatus = newCase.Status;
            if (newCase.OppToCase__c != null && oldMap != null) {
                Case oldCase = oldMap.get(newCase.Id);
                for (String fieldName: schemaFieldMap.keySet()) {
                    String fieldLabel = schemaFieldMap.get(fieldName).getDescribe().getLabel();
                    if (newCase.get(fieldName) != oldCase.get(fieldName) && fieldToSkip.contains(fieldLabel)) {
                        batchInputs.add(postOnOpportunityChatter(fieldLabel, String.valueOf(newCase.get(fieldName)), String.valueOf(oldCase.get(fieldName)), newCase.OppToCase__c, newcase.CaseNumber, String.valueOf(newcase.Request_Type__c),caseStatus));
                    }
                }
            }
        }
        if (!batchInputs.isEmpty()) {
            if(!Test.isRunningTest()) ConnectApi.ChatterFeeds.postFeedElementBatch(Network.getNetworkId(), batchInputs);
        }
    }

    public static ConnectApi.BatchInput postOnOpportunityChatter(String fieldLabel, String fieldNewValue, String fieldOldValue, Id opportunityID,String caseID,String caseType, String caseStatus) {

        List<Opportunity> Oppstatus = [SELECT StageName FROM Opportunity WHERE Id =: opportunityID];

        String closedWon = '';
        for(Opportunity pathStatus: Oppstatus){
            closedWon = pathStatus.StageName;
        }

        ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
        ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
        ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
        ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();
        messageBodyInput.messageSegments = new List < ConnectApi.MessageSegmentInput > ();

        ConnectApi.MarkupBeginSegmentInput markupBeginSegment = new ConnectApi.MarkupBeginSegmentInput();
        markupBeginSegment.markupType = ConnectApi.MarkupType.Bold;
        messageBodyInput.messageSegments.add(markupBeginSegment);

        textSegmentInput = new ConnectApi.TextSegmentInput();
        textSegmentInput.text = 'Scoping request '+ fieldLabel;
        messageBodyInput.messageSegments.add(textSegmentInput);

        ConnectApi.MarkupEndSegmentInput markupEndSegment = new ConnectApi.MarkupEndSegmentInput();
        markupEndSegment.markupType = ConnectApi.MarkupType.Bold;
        messageBodyInput.messageSegments.add(markupEndSegment);

        textSegmentInput = new ConnectApi.TextSegmentInput();
        textSegmentInput.text = ' was changed from ' + fieldOldValue + ' to ' + fieldNewValue+','+' Case ID:'+caseID+','+' Case Type:'+caseType ;
        if (caseStatus == 'Closed' && closedWon == 'Stage 8-Closed Won: Finance')textSegmentInput.text += ' Please submit your feedback about the Scoping Process here: https://www.surveymonkey.com/r/P99DSJW';
        messageBodyInput.messageSegments.add(textSegmentInput);
        feedItemInput.body = messageBodyInput;
        feedItemInput.feedElementType = ConnectApi.FeedElementType.FeedItem;
        feedItemInput.subjectId = opportunityID;
        return new ConnectApi.BatchInput(feedItemInput);
    }

}
Trigger Test Class:
@IsTest
public class CaseTriggerTest {
    
    @IsTest
    public static void insertCase () {
        Test.startTest();
        Account account1 = new Account(name = 'test');
        insert account1;
        Case case1 = new Case(Status = 'New', Origin = 'Phone', Priority = 'Medium', Request_Type__c = 'Redlines', Accurate_zQuote__c = true, SQD_Attached__c = true);
        Opportunity opp2 = new Opportunity(accountId = account1.Id, closeDate = Date.today(), stageName = 'Stage 1-Identified Opp', forecastCategoryName = 'Probable', name = 'test opp 1');
        case1.Status = 'Closed';
        opp2.Case__c = case1.Id;
        case1.OppToCase__c = opp2.Id;
        insert opp2;
        update opp2;
        insert case1;
        update case1;
        Test.stopTest();
    }
}

I am only getting 27% coverage and when I am trying to deploy it am getting an error I need 75%. Cam someone help thank you. 
 
Best Answer chosen by Haseeb Ahmad 9
Haseeb Ahmad 9Haseeb Ahmad 9
I am able to fix it by updating the apex class.
 
@IsTest
public class CaseTriggerTest {
    
    @IsTest
    public static void insertCase () {
        List<Profile> prof = [SELECT Id FROM Profile WHERE Name='Professional Services']; 
        User user = new User ();
        user.firstName = 'test1';
        user.lastName = 'test2';
        user.ProfileId = prof[0].Id ;
        user.Username = 'test@email4x.com' ;
        user.Email = 'test@email.com';
        user.Alias = 't1';
        user.EmailEncodingKey = 'ISO-8859-1';
        user.LocaleSidKey = 'en_US' ;
        user.TimeZoneSidKey = 'America/Los_Angeles';
        user.LanguageLocaleKey = 'en_US' ;
        Insert user ;
        system.runAs(user) {
            Test.startTest();
            Account account1 = new Account(name = 'test');
            insert account1;
            Case case1 = new Case(Status = 'New', Origin = 'Phone', Priority = 'Medium', Request_Type__c = 'Redlines', Accurate_zQuote__c = true, SQD_Attached__c = true);
            Opportunity opp2 = new Opportunity(accountId = account1.Id, closeDate = Date.today(), stageName = 'Stage 1-Identified Opp', forecastCategoryName = 'Probable', name = 'test opp 1');
            case1.Status = 'Closed';
            opp2.Case__c = case1.Id;
            case1.OppToCase__c = opp2.Id;
            insert opp2;
            update opp2;
            insert case1;
            update case1;
            Test.stopTest();
        }
    }
}

 

All Answers

AnudeepAnudeep (Salesforce Developers) 
Can you please highlight the lines that are not covered? Thanks
Haseeb Ahmad 9Haseeb Ahmad 9
HI Aundeep,

Thank you for your reply.

These lines are not covered.
 
switch on Trigger.operationType {
        when BEFORE_INSERT {
            CaseHelper.checkCaseAssignedRulesInsert(trigger.new);
        }
        when BEFORE_UPDATE{
            CaseHelper.checkCaseAssignedRulesInsert(trigger.new);
            CaseHelper.timestamp(trigger.new);
        }
        when AFTER_UPDATE {
            CaseHelper.checkCasePostUpdatesData(Trigger.oldMap, trigger.new);
        }
    }

 
Haseeb Ahmad 9Haseeb Ahmad 9
I am able to fix it by updating the apex class.
 
@IsTest
public class CaseTriggerTest {
    
    @IsTest
    public static void insertCase () {
        List<Profile> prof = [SELECT Id FROM Profile WHERE Name='Professional Services']; 
        User user = new User ();
        user.firstName = 'test1';
        user.lastName = 'test2';
        user.ProfileId = prof[0].Id ;
        user.Username = 'test@email4x.com' ;
        user.Email = 'test@email.com';
        user.Alias = 't1';
        user.EmailEncodingKey = 'ISO-8859-1';
        user.LocaleSidKey = 'en_US' ;
        user.TimeZoneSidKey = 'America/Los_Angeles';
        user.LanguageLocaleKey = 'en_US' ;
        Insert user ;
        system.runAs(user) {
            Test.startTest();
            Account account1 = new Account(name = 'test');
            insert account1;
            Case case1 = new Case(Status = 'New', Origin = 'Phone', Priority = 'Medium', Request_Type__c = 'Redlines', Accurate_zQuote__c = true, SQD_Attached__c = true);
            Opportunity opp2 = new Opportunity(accountId = account1.Id, closeDate = Date.today(), stageName = 'Stage 1-Identified Opp', forecastCategoryName = 'Probable', name = 'test opp 1');
            case1.Status = 'Closed';
            opp2.Case__c = case1.Id;
            case1.OppToCase__c = opp2.Id;
            insert opp2;
            update opp2;
            insert case1;
            update case1;
            Test.stopTest();
        }
    }
}

 
This was selected as the best answer