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
Phani Pydimarry 4Phani Pydimarry 4 

Help in writing a test class for a Future Meathod

Hello,

I am very new to Salesforce Development. I have the following class where I post Name and Email to a rest service. Please help me in writing a test class.
public class PD_WelcomeMaroPost {
   
    @future(callout=true)
    public static void sendEmailThroughMaro(string myInpEmail) {
        string successContacts = '';
        string failureContacts = '';
        
        List<Stripe_Subscripton__c> subsToUpdate = new List<Stripe_Subscripton__c>();
        //List<Case> newCase = new List<Case>();
        
        
        // SQL to fetch FBO who Joined Today
        list<Account> conts = new list<Account> ([SELECT Id, name, Email_FLP_com__c,
        (SELECT Id
        FROM Stripe_Subscriptons__r
        WHERE Start_Date__c= TODAY
            AND Status__c='active'
            AND Welcome_Email__C = false
        LIMIT 1)
    from account
    where ID IN (
        select Distributor__c
        from Stripe_Subscripton__c
        where Start_Date__c= TODAY
            AND Status__c='active'
            AND Welcome_Email__C = false)
    AND  Email_FLP_com__c != NULL
    LIMIT 100]);
            
		system.debug('>>>>>>>>>>' + conts);
        overallEmail myEmail = new overallEmail();
       
        for(Account c : conts){
           string resultBodyGet = '';
            myEmail.email.campaign_id = 172;
            
            myEmail.email.contact.Email = c.Email_FLP_com__c;
            myEmail.email.contact.first_name = c.name;
            
            /**MAp<String, String> tags = new Map<String, String>();
            tags.put('firstName', c.name);
            myEmail.email.tags = tags;**/
            system.debug('#### Input JSON: ' + JSON.serialize(myEmail));
            
            
            try{
                String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
                HttpRequest req = new HttpRequest();
                req.setEndpoint(endpoint);
                req.setMethod('POST');
                req.setHeader('Content-type', 'application/json');
                req.setbody(JSON.serialize(myEmail));
                Http http = new Http();
                system.debug('Sending email');
                HTTPResponse response = http.send(req); 
                system.debug('sent email');
                 resultBodyGet = response.getBody();
                system.debug('Output response:' + resultBodyGet);
                maroResponse myMaroResponse = new maroResponse();
                myMaroResponse = (maroResponse) JSON.deserialize(resultBodyGet, maroResponse.class);
                system.debug('#### myMaroResponse: ' + myMaroResponse);
                if(myMaroResponse.message == 'Email was sent successfully')
                   successContacts = successContacts + ';' + c.Email_FLP_com__c;
                else
                    failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
            }
            catch (exception e) {
                failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
                system.debug('#### Exception caught: ' + e.getMessage());                
            }
            
            c.Stripe_Subscriptons__r[0].Welcome_Email__c = true;
            c.Stripe_Subscriptons__r[0].Welcome_Email_Sent_Date__c = system.today();
    		subsToUpdate.add(c.Stripe_Subscriptons__r[0]);
            
              /** Case cs = new Case();       
               cs.RecordTypeId = '012m00000008ja9';
               cs.Status = 'Welcome Email Sent';
               cs.AccountId = c.Id;
               cs.OwnerId = '00Gm000000167FL';
               cs.Subject = 'FLP360 New User';
               cs.Description = resultBodyGet;
               cs.origin = 'Email';
               cs.Reason = 'New FLP360 Subscription';
               cs.Case_Sub_Reason__c = 'Email Notification';
               newCase.add(cs);**/
       
        }
       
        Update subsToUpdate;
        //insert newCase;
       // system.debug('newCase');
       
                 
    }
    
    public class maroResponse {
        public string message {get;set;}
    }

    public class overallEmail {
        public emailJson email = new emailJson();
    }
    
    public class emailJson {
        public Integer campaign_id;
        
        public contactJson contact = new contactJson();
       //Public Map<String, String> tags;
    }
    
    public class contactJson {
        public string email;
        public string first_name;
    }
    
}

 
Best Answer chosen by Phani Pydimarry 4
Raj VakatiRaj Vakati
here is the code
 
@IsTest
private class PD_WelcomeMaroPost_test {

  @IsTest
  private static void testemail() {
  
  Account a = new Account();
  a.Name ='Test' ;
  a.Email_FLP_com__c = 'test@nextsphere.com';
  insert a ; 
      
  Stripe_Subscripton__c s = new Stripe_Subscripton__c();
 
 // insert subscription --
 S.Welcome_Email__c = TRUE;
 S.Welcome_Email_Sent_Date__c = system.today();
 INSERT S;
  
    Test.setMock(HttpCalloutMock.class, new PD_WelcomeMaroPostMock());
    Test.startTest();

PD_WelcomeMaroPost.sendEmailThroughMaro('test@nextsphere.com');


    Test.stopTest();
   
   }

}

 

All Answers

Raj VakatiRaj Vakati
Sample code is here below. Refer this link for more info 
https://trailhead.salesforce.com/en/modules/asynchronous_apex/units/async_apex_future_methods 


 
@isTest
public class PD_WelcomeMaroPostMock implements HttpCalloutMock {
    global HttpResponse respond(HttpRequest req) {
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"status":"success"}');
        res.setStatusCode(200);
        return res; 
    }
}



@IsTest
private class PD_WelcomeMaroPost_Test {

  @IsTest
  private static void testSendSms() {
  
  Account a = new Account();
  a.Name ='Test' ;
  insert a ; 
  
 Stripe_Subscripton__c s = new Stripe_Subscripton__c();
 // insert subscription --
  
    Test.setMock(HttpCalloutMock.class, new PD_WelcomeMaroPostMock());
    Test.startTest();

PD_WelcomeMaroPost.myInpEmail('test@email.com');


    Test.stopTest();
   
   }

}

 
Phani Pydimarry 4Phani Pydimarry 4
Thanks a ton for the response. I am getting the following errors for the code I have used below
I am getting a " Missing '<EOF>' at '@' " error at line 13
" Defining type for global methods must be declared as global" at line 3

Please help me
@isTest
public class PD_WelcomeMaroPostMock implements HttpCalloutMock {
    global HttpResponse respond(HttpRequest req) {
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"status":"success"}');
        res.setStatusCode(200);
        return res; 
    }
}

	@IsTest
private class PD_WelcomeMaroPost_Test {

  @IsTest
  private static void testemail() {
  
  Account a = new Account();
  a.Name ='Test' ;
  a.Email_FLP_com__c = 'ppydimarry@nextsphere.com';
  insert a ; 
      
  Stripe_Subscripton__c s = new Stripe_Subscripton__c();
 
 // insert subscription --
 S.Welcome_Email__c = TRUE;
 S.Welcome_Email_Sent_Date__c = TODAY
 INSERT S;
  
    Test.setMock(HttpCalloutMock.class, new PD_WelcomeMaroPostMock());
    Test.startTest();

PD_WelcomeMaroPost.myInpEmail('ppydimarry@nextsphere.com');


    Test.stopTest();
   
   }

}

 
Phani Pydimarry 4Phani Pydimarry 4
I changed Global to Public and the error is no more. But Why I am I getting this eeror at line 13?
Raj VakatiRaj Vakati
Thow two different classes... Not single class 
Raj VakatiRaj Vakati

Those two different classes... Not single class 

Refer this link on how to setup test data for callouts 

​https://trailhead.salesforce.com/en/modules/asynchronous_apex/units/async_apex_future_methods 
 
Phani Pydimarry 4Phani Pydimarry 4
Thanks Raj,

I must admit I am very ordinory at this and I am learning from you. I created two classes and now the test class says 
Method does not exist or incorrect signature: void myInpEmail(String) from the type PD_WelcomeMaroPost
 
@IsTest
private class PD_WelcomeMaroPost_test {

  @IsTest
  private static void testemail() {
  
  Account a = new Account();
  a.Name ='Test' ;
  a.Email_FLP_com__c = 'test@nextsphere.com';
  insert a ; 
      
  Stripe_Subscripton__c s = new Stripe_Subscripton__c();
 
 // insert subscription --
 S.Welcome_Email__c = TRUE;
 S.Welcome_Email_Sent_Date__c = system.today();
 INSERT S;
  
    Test.setMock(HttpCalloutMock.class, new PD_WelcomeMaroPostMock());
    Test.startTest();

PD_WelcomeMaroPost.myInpEmail('test@nextsphere.com');


    Test.stopTest();
   
   }

}

 
Raj VakatiRaj Vakati
here is the code
 
@IsTest
private class PD_WelcomeMaroPost_test {

  @IsTest
  private static void testemail() {
  
  Account a = new Account();
  a.Name ='Test' ;
  a.Email_FLP_com__c = 'test@nextsphere.com';
  insert a ; 
      
  Stripe_Subscripton__c s = new Stripe_Subscripton__c();
 
 // insert subscription --
 S.Welcome_Email__c = TRUE;
 S.Welcome_Email_Sent_Date__c = system.today();
 INSERT S;
  
    Test.setMock(HttpCalloutMock.class, new PD_WelcomeMaroPostMock());
    Test.startTest();

PD_WelcomeMaroPost.sendEmailThroughMaro('test@nextsphere.com');


    Test.stopTest();
   
   }

}

 
This was selected as the best answer
Phani Pydimarry 4Phani Pydimarry 4
Thanks a ton. My test class is passed with a 28% code coverage. I have all the insert operations passed but my JSON or the below code is still red. 
 
try{
                String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
                HttpRequest req = new HttpRequest();
                req.setEndpoint(endpoint);
                req.setMethod('POST');
                req.setHeader('Content-type', 'application/json');
                req.setbody(JSON.serialize(myEmail));
                Http http = new Http();
                system.debug('Sending email');
                HTTPResponse response = http.send(req); 
                system.debug('sent email');
                 resultBodyGet = response.getBody();
                system.debug('Output response:' + resultBodyGet);
                maroResponse myMaroResponse = new maroResponse();
                myMaroResponse = (maroResponse) JSON.deserialize(resultBodyGet, maroResponse.class);
                system.debug('#### myMaroResponse: ' + myMaroResponse);
                if(myMaroResponse.message == 'Email was sent successfully')
                   successContacts = successContacts + ';' + c.Email_FLP_com__c;
                else
                    failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
            }
            catch (exception e) {
                failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
                system.debug('#### Exception caught: ' + e.getMessage());                
            }