+ Start a Discussion
Vijay Kumar Rebbala 1Vijay Kumar Rebbala 1 

Test class for try catch and final block

global class DeleteoldCases{
    Public void SFDCDeleteoldCases(){
        List<Case> QueryCases = [SELECT Id FROM Case WHERE CreatedDate < LAST_N_MONTHS:18 ORDER BY CreatedDate ASC  LIMIT 9000];
        Integer QueryCount = database.countQuery('SELECT Count() FROM Case WHERE CreatedDate < LAST_N_MONTHS:18  LIMIT 9000');
            If (QueryCases.isEmpty())
                delete QueryCases;
            }catch(DmlException e) {
                System.debug('An unexpected error has occurred: ' + e.getMessage());  
            }catch(NullPointerException npe) {
                System.debug('The following exception has occurred: ' + npe.getMessage());         
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();         
            String[] toAddresses = new String[] {'CSAdmins@zynga.com'};        
            mail.setSubject('Salesforce ZRM CaseDelete Status');         
            mail.setPlainTextBody('The Scheduled Apex job processed ' +QueryCount);         
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

Test Class:

public Class testDeleteoldCases {
    public static testMethod void testschedule() {  
        DeleteoldCases delca = new DeleteoldCases();
        Case newcase = new Case();
        newcase.Subject = 'Testing123456798';
        insert newcase;
List<Case> QueryCases = [SELECT Id FROM Case WHERE Subject = 'Testing123456798' ORDER BY CreatedDate ASC  LIMIT 9000];
        try {
            if(Test.isRunningTest()) {  
                QueryCases = null;
            delete QueryCases;
        } catch(Exception e) {           
            system.debug('Failed to delete cases');
You can't really do this kind of testing with Salesforce. In this case you'd need to insert a record that couldn't be deleted, which is obviously not possible.  They way I usually handle this is to move the query out to another method and provide a way to inject the results when running tests. In that situation the query doesn't run against the database, it simply returns my injected record(s) which can be missing an ID for example to cause the delete to fail.

I can't see how your code could throw a null pointer exception so I doubt you'll be able to test that.