+ Start a Discussion

Problems With TestMethods for @feature (callout=true) functions



I have trouble creating test methods for the following class.


global class scheduable_Tier1ChatExport implements Schedulable  {

    global void execute(SchedulableContext SC){

     public static void getChats(){
         Chat_Transcript_Export__c chat = new Chat_Transcript_Export__c (name = 'Tier1 '+ datetime.now(), Status__c='Not Processed');
        String fileBeingProccesed = '';
         datetime startDate = Datetime.now();     //today
        startDate=startDate.addDays(-1);         //yesterday
           upsert chat;
           Integer j=0;
           for(Integer i = 0; i<8; i++){
                fileBeingProccesed =  'Tier1 Chats N:'+i+' '+startDate.date();                                                
                String url='https://myurl.com&startDate='+startdate.year()+'-'+startdate.month()+'-'+startdate.day()+'T'+j+':00:00&endDate='+startdate.year()+'-'+startdate.month()+'-'+startdate.day()+'T'+(j+2)+':59:59&limit=5000&toZip=false';
                HttpRequest req = new HttpRequest();                
                Http http = new Http();
                HTTPResponse res = http.send(req);                     
                Attachment att = new Attachment (name = 'Tier1 Chats N:'+i+' '+startDate.date(), ParentId = chat.Id, Body =  Blob.valueof(res.getBody()));             
                insert att;
         catch(Exception e){
             chat.Export_Log__c = 'Errors were found: '+e.getMessage()+' On File: ' + fileBeingProccesed;
             upsert chat;


This class simply schedules an export for data coming from an external service and creates xml attachments on an obeject called Chat_transcript_export.

I call for 8 different exports because the amount of data can be too big and exceed the maximum timeout allowed by salesforce.


How can I create the test methods for this class?






In order to test methods with the future annotation, you'll need to use the Test.startTest() and Test.stopTest() methods - execute your methods that would queue the future method after a startTest, and they will be executed synchronously once stopTest() is called.


That said, you can't make callouts in test methods.  I tend to use the Test.IsRunningTest() method to determine if my code is running from a unit test.  If it isn't, I let the callout proceed as usual, if it is, I fake up the expected responses on the fly.