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
AD1418AD1418 

How to cover exception in test classes?

How to cover exception code in below class :- Below is apex class - 
public class CRM_ForecastCommentary {
    @AuraEnabled
    public static void saveLFCommentary(String liveForecastId , String comment){
        CRM_Live_Forecast__c[] LFlst = new List<CRM_Live_Forecast__c>();
        CRM_Live_Forecast__c FLtoUpdate;
        Id LFId = Id.valueOf(liveForecastId);
        try {
            insert LFlst;       
            FLtoUpdate =  [SELECT Name , Id , CRM_Comment__c FROM CRM_Live_Forecast__c
           WHERE Id =: LFId ];    
            // Update the comment.
            FLtoUpdate.CRM_Comment__c = comment;
            // Make the update call.
            update FLtoUpdate;
        } catch(DmlException e) {
            System.debug('An unexpected error has occurred: ' + e.getMessage());
            // Verify that the comment s updated.
            CRM_Live_Forecast__c afterUpdate = [SELECT CRM_Comment__c FROM CRM_Live_Forecast__c WHERE Id =: LFId];
            System.assertEquals(comment, afterUpdate.CRM_Comment__c);
            
        }
    }
	
    @AuraEnabled
    public static void saveCFCommentary(String commitForecastId , String comment){
        CRM_Committed_Forecast__c[] CFlst = new List<CRM_Committed_Forecast__c>();
        CRM_Committed_Forecast__c CFtoUpdate;
        Id CFId = Id.valueOf(commitForecastId);
        try {
            insert CFlst;       
            CFtoUpdate =  [SELECT Name , Id , CRM_Comment__c FROM CRM_Committed_Forecast__c
                 WHERE Id =: CFId ];    
            // Update the comment.
            CFtoUpdate.CRM_Comment__c = comment;
            // Make the update call.
            update CFtoUpdate;
        } catch(DmlException e) {
            System.debug('An unexpected error has occurred: ' + e.getMessage());
            // Verify that the comment s updated.
            CRM_Committed_Forecast__c afterUpdate = [SELECT CRM_Comment__c FROM CRM_Committed_Forecast__c WHERE Id =: CFId];
            System.assertEquals(comment, afterUpdate.CRM_Comment__c);
            
        }
    }
}

Below is test class. All is covered except ​​​exceptions.
@isTest
public class CRM_ForecastCommentaryTest {
    
    static testmethod void testSaveLFCommentary(){

        // insert forecast assignment test data
        CRM_Forecast_Assignment__c fassignment = new CRM_Forecast_Assignment__c();
        fassignment.Name = 'test FA';
        insert fassignment;
        system.assert(fassignment.Id != null);

        // insert Forecast period test data
        CRM_Forecast_Period__c fperiod = new CRM_Forecast_Period__c();
        fperiod.Name = 'test forecast period';
        fperiod.CRM_Fiscal_Year__c = '2020';
        fperiod.CRM_Fiscal_Quarter__c = 'FY2020 Q1';
        insert fperiod;
        system.assert(fperiod.Id != null);

        // create live forecast test data
        CRM_Live_Forecast__c liveForecast = new CRM_Live_Forecast__c();
        liveForecast.CRM_Forecast_Assignment__c	 = fassignment.Id;
        liveForecast.CRM_Forecast_Period__c = fperiod.Id;
        liveForecast.CRM_Comment__c = 'test comment';
        insert liveForecast;
        system.assert(liveForecast.Id != null);

        test.startTest();
        CRM_ForecastCommentary.saveLFCommentary(liveForecast.Id, 'testcomment');
        test.stopTest();
    }

    static testmethod void testSaveCFCommentary(){

        // insert forecast assignment test data
        CRM_Forecast_Assignment__c fassignment = new CRM_Forecast_Assignment__c();
        fassignment.Name = 'test FA';
        insert fassignment;
        system.assert(fassignment.Id != null);

        CRM_Committed_Forecast__c commitFA = new CRM_Committed_Forecast__c();
        commitFA.CRM_Comment__c = 'Forecast Committed';
        commitFA.CRM_Forecast_Assignment__c = fassignment.Id;
        try{
            insert commitFA;
            system.assert(commitFA.Id != null);
        } catch(DmlException e){
            system.assertEquals(e.getMessage(), e.getMessage());
        
        }
        test.startTest();
        CRM_ForecastCommentary.saveCFCommentary(commitFA.Id, commitFA.CRM_Comment__c );
        test.stopTest();

    }
}
ShirishaShirisha (Salesforce Developers) 
Hi Amiya,

Greetings!

Please note that Not all code that is written can be covered. This is a fact of salesforce.com development. There is a reason why the deployment rule is 75% coverage, and not 100% coverage.

However,if you would like to cover the exception then you can try the  sample code given in the below document:

https://developer.salesforce.com/forums/?id=9060G000000UY64QAG

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Warm Regards,
Shirisha Pathuri
Sachin HoodaSachin Hooda
So, the exception part will be covered only if an exception will occur. So, you can either ignore it simply.
OR if you still want to cover it, for the sake of your own satisfaction or you want the coverage to be 100%. You simply need to generate the exception. 
So in order to do so
I've made some changes to the code, Please try this & let me know if it worked. 
So please add this method to your test class & try executing both methods.
static testmethod void testSaveCFCommentary_Excepion(){

        CRM_Forecast_Assignment__c fassignment = new CRM_Forecast_Assignment__c();
        fassignment.Name = 'test FA';
        insert fassignment;
        system.assert(fassignment.Id != null);

        CRM_Committed_Forecast__c commitFA = new CRM_Committed_Forecast__c();
        commitFA = null; //generates exception
        try{
            insert commitFA;
            system.assert(commitFA.Id != null);
        } catch(DmlException e){
            system.assertEquals(e.getMessage(), e.getMessage());
        
        }

I hope it covered the exception part as well. If it didn't work. Let me know the issue.
Regards,
Sachin
(:
Happy to Help!
Archana BattaArchana Batta
Hi @Amiya Das 1418,

Try passing long text in your second parameter (Comment) than what is expected. I mean, if your CRM_Comment__c length on CRM_Committed_Forecast__c object is 10. Pass a text that is longer than 10. It would throw an exception saying Data value is too large.

Hope this helps.

Thanks & Regards,
Archana
 
Maharajan CMaharajan C
Hi Amiya,

Pass the dummy Salesforce record id toliveForecastId and commitForecastId arguments then it will give the error message. Because you are Querying the CRM_Live_Forecast__c and CRM_Committed_Forecast__c records in the class and refering the CRM_Comment__c  field from the record to update. So it will generate the List has no rows for assignment to SObject error and it will cover the Exception.

To cover the Exception lines in your class add  one more test method. The Method should be like below:

@isTest 
public class CRM_ForecastCommentaryTest {
    Static testmethod void ExceptionsTestMethod(){
        CRM_ForecastCommentary.saveLFCommentary('0010o00002iZjtQ', 'testcomment');
        CRM_ForecastCommentary.saveCFCommentary('0010o00002iZjtQ', 'testcomment' );
    }
}​​​​​​​

Thanks,
Maharajan,C
AD1418AD1418
Thanks a lot for response. Didn't worked. Test class execution fails with error - System.QueryException: List has no rows for assignment to SObject. and class coverage is same.
Maharajan CMaharajan C
Hi Amiya,

Can you please tell me at which line number you are getting this exception in Class.

Thanks,
Maharajan.C