+ Start a Discussion
ashish raiashish rai 

How to write the Test Method that call @future method????

Hi All,

I have written a trigger on opportunity and inside the trigger i have called @future method of a class.I am unable to test my trigger.

 

trigger ConfirmationEmailContentTrigger on Opportunity (after insert,before update)
{

List<Opportunity> listOpp = new List<Opportunity>();
list<id> ids=new list<id>();
for (Opportunity op: trigger.new)
{
ids.add(op.id);
if(Trigger.isInsert)
{
Opportunity oppNew = [SELECT Id, StageName FROM Opportunity WHERE Id =:op.Id];
//oppNew.Confirmation_Email_Content__c = '';
system.debug('Opportunity Value'+op.AccountId);
if(op.AccountId != null)
{
Account acc = [SELECT Id FROM Account WHERE Id =:op.AccountId limit 1];
system.debug('Account Value'+acc);
if(acc != null)
{
Contact[] con = [SELECT Id, Email FROM Contact WHERE AccountId =:acc.id order by CreatedDate asc limit 1];
if (con.size() > 0)
{
//oppNew.Email__c = con[0].Email;
//oppNew.Notification_Email_Address__c = con[0].Email;
}
}
}
listOpp.add(oppNew);
if (listOpp != null && !listOpp .isEmpty())
{
Database.update(listOpp);
}
}
else if(op != null && Trigger.isUpdate)
{

if(op.StageName == 'Tickected')
{

string result='';

}

}

}
if(ids.size() > 0)
CallFromTriggerTest.updateContact(ids);
}

 

//////////////////////// Apex Class having @future    ////////////////////////////

public class CallFromTriggerTest
{
@future(callout=true)
public static void updateContact(list<id> usercontactid )
{
system.debug('@@@@@@@@@@@@@@@@@' +usercontactid );
string result='';
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('http://abc.com?id=');//+op.Id);
req.setMethod('GET');

HttpResponse res = h.send(req);
result = res.getBody();
}
static testmethod void coverClass()
{

Account a=new Account(name='test');
insert a;
List<id> listOpp = new List<id>();
Opportunity op=new Opportunity(name='testOpp',CloseDate=system.today(),StageName='Tickected',accountid=a.id);
insert op;
listOpp.add(op.id);
//CallFromTriggerTest c=new CallFromTriggerTest();
CallFromTriggerTest.updateContact(listOpp);
}
}

 

Please help me  for test the trigger.

 

KapilCKapilC

Hi Ashish,

 

To test methods defined with the future annotation, call the class containing the method in a startTest, stopTest code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.

 

 

[If you got answer from my post please mark it as solution.]
Thanks,
Kapil
ashish raiashish rai

Hi Kapil,

Thanx for your quick reply but my question is i am unable to cove the Trigger. I have already written the test code for @future method which is working fine. Now i want to cover my trigger. Please help me to write the test method for trigger.