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
Loz ICOLoz ICO 

Test API Call (@Future(callout=true))

Dears

 

I need to release this api call for our client, the coverage of my test is 67%, like you know I need at least 75% how I can get the 75%? Below the code.

 

public class APICall {

 
  //Future annotation to mark the method as async.
  @Future(callout=true)


//  String id, String name
public static void APICall_Request (Datetime fecha_inicio, Datetime fecha_fin, string Event_Id, string account_Id) {

        HttpRequest req = new HttpRequest();
 
        req.setEndpoint('https://apisphere.locationsmart.com/restapi/v_1_1/sphere');
        req.setMethod('POST');
        

/****getting info from table Account***/

      List<account> b = [Select latitud__c, Longitud__c From Account Where Id=:account_Id];
 

    string latitud = b[0].latitud__c; //info for the XML
    string Longitud = b[0].Longitud__c; //info for the XML
      
    /****converting the datetimne*******/
    Datetime fecha_fin_def   = fecha_fin.AddHours(1);//time dif our time -4:30 GMT (time difference with your servers and salesforce)
    Datetime fecha_inic_def  = fecha_inicio.AddHours(-1);//time dif -4:30 GMT (time difference with your servers and salesforce)
    
/******** XML*******/
      req.setBody( '<request>    <authentication>        <username>65460806</username>        <password>hello</password>    </authentication>    <sphere>        <name>'+Event_Id+'</name>  <campaign>DEMO</campaign>      <onEnter>           <processId>6540088</processId>          <processPayload>&lt;payload&gt;&lt;value&gt;'+Event_Id+'&lt;/value&gt;&lt;/payload&gt;</processPayload>        </onEnter>        <onExit>            <processId>6540088</processId>           <processPayload>&lt;payload&gt;&lt;value&gt;'+Event_Id+'&lt;/value&gt;&lt;/payload&gt;</processPayload>      </onExit>        <device>65460806</device>                <zone>            <address>'+Longitud+' '+latitud+'</address>            <radius>90</radius>            <unitType>mtrs</unitType>        </zone>        <startDate>'+fecha_inic_def+' +0000</startDate>        <endDate>'+fecha_fin_def+' -0000</endDate>    </sphere></request>');

        // Create a new http object to send the request object
        // A response object is generated as a result of the request
        Http http = new Http();
        HTTPResponse res = http.send(req);
        req.setMethod('POST');

 

/********************** the result is ok sucessful this function and the connection is working fine *************************/

 

     //check the response
    if (res.getStatusCode() == 200) {
      System.debug('Exitoso '+ res);

// checking the result
      Event acc = new Event(Id='00US00000014KqmMAE');
     acc.Description = ' Created '+datetime.now()+'  '+res.getBody()+' inicio '+fecha_inicio+'  fin '+fecha_fin+' lat '+latitud+' long '+Longitud ;

       try {
               update acc;
      
               
            } catch (DmlException e) {
                //Assert Error Message
                System.assert( e.getMessage().contains('Update error'),
                e.getMessage());
            }//catch
      


    } else {
      System.debug('Callout failed: ' + res);
// checking the result      
      Event acc = new Event(Id='00US00000014KqmMAE');
      acc.Description = 'Malo '+res.getBody();

       try {
               update acc;
            } catch (DmlException e) {
                //Assert Error Message
                System.assert( e.getMessage().contains('Update error'),
                e.getMessage());
            }//catch
      
    }
    
 
    

    }///api Call
    
    
}///class

 

/**************************************test mehotd*****************************/

 

 

 

@isTest
private class TestApiCall
 {
  //Added for security review
 
   public static testMethod void TestAPICall() {
    
        // TO DO: implement unit test

 

     Datetime fecha_inicio = datetime.now();
     Datetime fecha_fin = datetime.now();
     string Event_Id = '00UA00000041osdMAA';
     string account_Id = '001A000000LKjdeIAD';
     
     APICall.APICall_Request(fecha_inicio, fecha_fin, Event_Id, account_Id); /// after add this I increase the coverage from 53 % to 67%
     
     List<Account> b = [Select latitud__c, Longitud__c, Id From Account Where Id='001A000000LKjgIIAT'];

    string latitud = b[0].latitud__c;
    string Longitud = b[0].Longitud__c;
     
     List<Event> t = [Select EndDateTime, StartDateTime, Id, WhatId From Event Where Id='00UA00000041oscMAA'];


    Datetime fecha_fint    = t[0].EndDateTime;
    Datetime fecha_iniciot = t[0].StartDateTime;
    string Event_Idt= t[0].Id;
    string account_Idt = t[0].WhatId;


     
    APICall.APICall_Request(fecha_iniciot, fecha_fint, Event_Idt, account_Id); //adding this new line still have 67%
     
        
           Account acc2 = new Account(Id='001A000000LKjgIIAT');
           acc2.name = 'ANVA CELULAR, C.A.';
           acc2.latitud__c = '654897' ;
            acc2.Longitud__c = '98732100' ;
            
            acc2.Categoria__c = 'Uno (1)';
            acc2.Estatus__c = 'Operativo';
            acc2.Region__c ='GRAN CARACAS';
            acc2.Zona__c = 'ZONA METROPOLITANA';
            acc2.Tipo__c = 'AA - Agente Autorizado';
            
            try {
               update acc2;
            } catch (DmlException e) {
                //Assert Error Message
                System.assert( e.getMessage().contains('Update error'),
                e.getMessage());
            }//catch
 
        
        acc2 = [Select name from Account where Id=:acc2.Id];  
        System.debug('Nombre: ' + acc2.name);
        System.assertEquals('ANVA CELULAR, C.A.', acc2.name);
        
        
         

        
          Account acc3 = new Account(Id='001A000000P2qYeIAJ');
           acc3.name = 'EQUIPOS ELECTRONICOS GLENOS, C.A.';
           acc3.latitud__c = '654897' ;
            acc3.Longitud__c = '98732100' ;
            
            acc3.Categoria__c = 'Uno (1)';
            acc3.Estatus__c = 'Operativo';
            acc3.Region__c ='GRAN CARACAS';
            acc3.Zona__c = 'ZONA METROPOLITANA';
            acc3.Tipo__c = 'AA - Agente Autorizado';
            update acc3;
        
        acc3 = [Select name from Account where Id=:acc3.Id];  
        System.debug('Nombre: ' + acc3.name);
        System.assertEquals('EQUIPOS ELECTRONICOS GLENOS, C.A.', acc3.name);


     
    
    }
    
    }//test class

 

Thanks in Advance

 

 

Best Answer chosen by Admin (Salesforce Developers) 
_Prasu__Prasu_

@Future(callout=true) need to be added for the method which making the callout, it should not be used for test method.

All Answers

_Prasu__Prasu_

Checkout the following link:

http://wiki.developerforce.com/index.php/An_Introduction_to_Apex_Code_Test_Methods

 

Refer the section :Test methods and Apex callout.

 

you will require breaking the code in functions.

 

I hope this helps.

Loz ICOLoz ICO

This is the error I got after change the class according to the manual " Error: Error de compilación: Method does not exist or incorrect signature: APICallV2.buildWebServiceRequest() en la línea 10 columna 25"

 

If I eliminate the comments in the @Future I got this error "Error de compilación: Test method cannot be marked as future en la línea 8 columna 24"

 

public class APICallV2 {

 
  //Future annotation to mark the method as async.
 // @Future(callout=true) //


static testMethod void testWebService(){
      //First, build the http request
      HttpRequest req = buildWebServiceRequest();
   
      //NOTE - WE DO NOT EXECUTE THE METHOD, invokeWebService.
      
      //Now, since we can't execute the actual web service,
      //write apex code to build a sample HttpResponse object
      HttpResponse res = new HttpResponse();
      //Apply test data and attributes to the HttpResponse object as needed
      handleWebServiceResponse(res);
 
}



 

public HttpRequest buildWebServiceRequest(){
    
       //Build HTTP Request object
//       HttpRequest req = new HttpRequest();
        HttpRequest req = new HttpRequest();
      // req.setEndpoint(<insert endpoint url here>);
        req.setEndpoint('https://apisphere.locationsmart.com/restapi/v_1_1/sphere');
      // req.setMethod('GET');
       req.setMethod('POST');
       return req;
   }
   
   public HttpResponse invokeWebService(Http h, HttpRequest req,Datetime fecha_inicio, Datetime fecha_fin, string Event_Id, string account_Id){
     
     //Invoke Web Service
   //  HttpResponse res = h.send(req);
    // return res;
     

      List<account> b = [Select latitud__c, Longitud__c From Account Where Id=:account_Id];

    string latitud = b[0].latitud__c;
    string Longitud = b[0].Longitud__c;
      
    
    Datetime fecha_fin_def   = fecha_fin.AddHours(1);//time dif our time -4:30 GMT (time difference with your servers and salesforce)
    Datetime fecha_inic_def  = fecha_inicio.AddHours(-1);//time dif -4:30 GMT (time difference with your servers and salesforce)
    
 
      req.setBody( '<request>    <authentication>        <username>333</username>        <password>dd</password>    </authentication>    <sphere>        <name>'+Event_Id+'</name>  <campaign>ccc</campaign>      <onEnter>           <processId>495320073</processId>          <processPayload>&lt;payload&gt;&lt;value&gt;'+Event_Id+'&lt;/value&gt;&lt;/payload&gt;</processPayload>        </onEnter>        <onExit>            <processId>333</processId>           <processPayload>&lt;payload&gt;&lt;value&gt;'+Event_Id+'&lt;/value&gt;&lt;/payload&gt;</processPayload>      </onExit>        <device>333</device>                <zone>            <address>'+Longitud+' '+latitud+'</address>            <radius>90</radius>            <unitType>mtrs</unitType>        </zone>        <startDate>'+fecha_inic_def+' +0000</startDate>        <endDate>'+fecha_fin_def+' -0000</endDate>    </sphere></request>');

        // Create a new http object to send the request object
        // A response object is generated as a result of the request
        Http http = new Http();
        HTTPResponse res = http.send(req);
        req.setMethod('POST');
        
        return res;
     
     
}

public void handleWebServiceResponse(HttpResponse res){

     //Parse and apply logic to the res message
      if (res.getStatusCode() == 200) {
      System.debug('Exitoso '+ res);

// checking the result
      Event acc = new Event(Id='00US00000014KqmMAE');
     acc.Description = ' Created '+datetime.now()+'  '+res.getBody();

       try {
               update acc;
                   
            } catch (DmlException e) {
                //Assert Error Message
                System.assert( e.getMessage().contains('Update error'),
                e.getMessage());
            }//catch
      


    } else {
      System.debug('Callout failed: ' + res);
// checking the result      
      Event acc = new Event(Id='00US00000014KqmMAE');
      acc.Description = 'Malo '+res.getBody();

       try {
               update acc;
            } catch (DmlException e) {
                //Assert Error Message
                System.assert( e.getMessage().contains('Update error'),
                e.getMessage());
            }//catch
      
    }
    
     
}
   
}//class

 

 

Anybody can help me with this issue.

 

Thanks in advances

_Prasu__Prasu_

@Future(callout=true) need to be added for the method which making the callout, it should not be used for test method.

This was selected as the best answer
nicloznicloz

Thanks thas was the solution the manual.