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
ezhil_kezhil_k 

How to Write test class for @future method...

@Future (callout=true)  
    public static void futuremethod(id conid){ 
    
      Httprequest request = new Httprequest();
      request.setMethod('GET');
      request.setEndpoint(LoopbackSite__c.getOrgDefaults().loopbackEndpoint__c +'/Self?conid='+conid);
      Httpresponse response = new Http().send(request); 
  }     
Best Answer chosen by Admin (Salesforce Developers) 
GlynAGlynA

Put the call to the future method inside startTest/stopTest:

 

Test.startTest();

myClass.futuremethod( someID );

Test.stopTest();

Test.stopTest() does not return until your future method has completed.

 

Your other problem will be that you can't make an actual web callout while testing.  Use "Test.isRunningTest()" to determine whether to make the callout:

if ( !Test.isRunningTest() ) new Http().send(request);

I wrote it this way because in your example, you don't use the HttpResponse that's returned...

 

If this helps, please mark it as a solution, and give kudos (click on the star) if you think I deserve them. Thanks!

 

-Glyn Anderson
Certified Salesforce Developer | Certified Salesforce Administrator

All Answers

GlynAGlynA

Put the call to the future method inside startTest/stopTest:

 

Test.startTest();

myClass.futuremethod( someID );

Test.stopTest();

Test.stopTest() does not return until your future method has completed.

 

Your other problem will be that you can't make an actual web callout while testing.  Use "Test.isRunningTest()" to determine whether to make the callout:

if ( !Test.isRunningTest() ) new Http().send(request);

I wrote it this way because in your example, you don't use the HttpResponse that's returned...

 

If this helps, please mark it as a solution, and give kudos (click on the star) if you think I deserve them. Thanks!

 

-Glyn Anderson
Certified Salesforce Developer | Certified Salesforce Administrator

This was selected as the best answer
farukh sk hdfarukh sk hd
To test future method,we need to call future method between test.startTest() and test.stopTest().
When test.startTest() runs data is collected asynchronously and as soon as test.stopTest runs data collected is 
run synchronously.

test.startTest();

myClass.futureMethodName(id);

test.stopTest();


For more information visit,

https://www.sfdc-lightning.com/2018/10/future-methods-in-salesforce.html