2

Folks,

I wonder if we have another way to create test class if we don't annotate with (SeeAllData=true).

Here, my SOQL to retrieve a list of ContentDocument have been created more than 7 days. That means we cannot use Date.newInstance() to set value for Created Date field.

My solution: Because we cannot modified Created Date so I use (SeeAllData=true). My code got covered 100%. But without it, it cannot cover anything.

My Batchable & Schedulable Class

public class deleteFileScheduler implements Database.Batchable<sObject>, Schedulable {

    public Database.QueryLocator start(Database.BatchableContext context){
        
        return Database.getQueryLocator([SELECT Id, Title, CreatedDate,contentSize
                                         FROM ContentDocument
                                         WHERE (Title Like 'Rp%' OR Title Like 'PDF%')
                                         AND CreatedDate < N_DAYS_AGO:7
                                        ]);
    }
    
    public void execute(Database.BatchableContext context, List<SObject> ContentDocument 
    {
        delete ContentDocument;
    }
    
    public void finish(Database.BatchableContext BC){}
    
    
    public void execute(SchedulableContext sc){
        Database.executeBatch(this);
    }
    
}

Test Class - Corverage 100% but annotate with (SeeAllData=true)

@isTest(SeeAllData=true)
public class deleteFileSchedulerTest {
    @isTest
    public static void deleteFileSchedulerTest(){
        String CRON_EXP = '0 0 4 * * ?';
        List<ContentDocument> docs = [SELECT Id, Title, CreatedDate, contentSize
                                      FROM ContentDocument
                                      WHERE (Title Like 'Rp%' OR Title Like 'PDF%')
                                      AND CreatedDate < N_DAYS_AGO:7];

        deleteFileScheduler deleteFile = new deleteFileScheduler();
        database.executeBatch(deleteFile);
        System.schedule('testschedule', '0 0 4 * * ?', new deleteFileScheduler());
        System.assertEquals(200, docs.size());
      } 
}

Thank you so much.

1 Answer 1

1

Use Test.setCreatedDate after inserting your record(s) to set the desired created date. Note that this specifically does not work with SeeAllData=true and cannot be used on records that were not created in that unit test.

1
  • Thank you so much for your solution
    – Pam
    Dec 5, 2022 at 13:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .