• Raja.P
  • NEWBIE
  • 10 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 2
    Replies
Hi folks,
Error: CalloutException: You have uncommitted work pending. Please commit or rollback before calling out
I am getting this error ,for test class :my logic is I am using restapi calls to make a callout and then based on the Response I am doing theDML operations in the salesforce
I have created the mock response also and used test.setmock  method but still my test class is failing  i wondering how to cover my code 
Class :
global class EZRE_MCEmailToAssignmentOwner
{
    public static Mailchimp_Details__c MCDtls{get;set;} 
    public static Map<String, String> mapCmpgnIdNme{get;set;} 
    public static Map<String,String> mapCmpgnIdFrmEml{get;set;}
    public static Map<String, Set<String>> mapCmpgnCndt{get;set;} 
    public static Set<String> setCmpgnId{get;set;}
    public static Set<String> setEmlAddrss{get;set;}
    public static MCCandidateList__c objInsrtMCCndt{get;set;}
      public static Set<String> setBouncedEmlAddrss{get;set;}
      public static HTTPResponse httpres{get;set;}
    ///OBJECTIVE
    ///getting the lsit of emails and the list of bounced and unsubscribed and opened emails  from mailchimp and update theresponse 
    ///OBJECTIVE
   @future (callout=true) 
    public static void sendMailToAssgnmntOwnr()
    {       
        getMCCmpngLst();
        getMCCampaignOpenList();  
        updateUnsubCand();
        updateBouncedCand();            
    }
    public static void getMCCmpngLst()
    {
        DateTime d = DateTime.Now().addDays(-5);       
        System.debug('d========================='+d);
        MCDtls = new Mailchimp_Details__c();
        MCDtls = EZRE_Data_Utility.getMCDtls('MCAccount');       
        Http h = new Http();        
        HttpRequest reqst = new HttpRequest();  
        reqst.setMethod('POST');       
        reqst.setBody('{"apikey": "'+MCDtls.API_Key__c+'","filters": {"status": "sent","sendtime_start": "'+d+'" },"sort_field": "create_time","sort_dir": "DESC"}');
        reqst.setEndpoint('https://'+MCDtls.Domain_Name__c+'.api.mailchimp.com/2.0/campaigns/list.JSON');
        HttpResponse res = new HttpResponse();
        res = h.send(reqst);              
            system.debug(':: Response for getting  campaign list:: ********'+res.getbody()); 
            mapCmpgnIdNme = new Map<String, String>();
            mapCmpgnIdFrmEml = new Map<String,String>();
            setCmpgnId = new Set<String>();
            Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
            List<Object> data = (List<Object>) m.get('data');        
            Map<String, Object> mapPgeDtls = new Map<String, Object>();           
            for (Object o : data) 
            { 
                mapPgeDtls = (Map<String, Object>) o;
                System.debug('>>> ' + mapPgeDtls);
                if((string.valueOf(mapPgeDtls.get('status'))) == 'sent')
                 {
                    mapCmpgnIdNme.put(string.valueOf(mapPgeDtls.get('id')),string.valueOf(mapPgeDtls.get('title')));
                    setCmpgnId.add(string.valueOf(mapPgeDtls.get('id')));  
                    mapCmpgnIdFrmEml.put(string.valueOf(mapPgeDtls.get('id')),string.valueOf(mapPgeDtls.get('from_email')));
                 } } 
         setEmlAddrss = new Set<String>(); 
        setBouncedEmlAddrss = new Set<String>(); 
        for(String str: setCmpgnId )
        {
            getMCCandUnsubscribesList(str);
            getMCCandBounceMessageList(str);
        } }
    
   public static void getMCCampaignOpenList()    
    {  
        MCDtls = new Mailchimp_Details__c();
        mapCmpgnCndt = new Map<String, Set<String>>();
        MCDtls = EZRE_Data_Utility.getMCDtls('MCAccount');       
        Http h = new Http();        
        HttpRequest reqst = new HttpRequest();  
        reqst.setMethod('POST');              
        reqst.setEndpoint('https://'+MCDtls.Domain_Name__c+'.api.mailchimp.com/2.0/reports/opened.JSON');
            for(String strCmpgn :setCmpgnId)  {         
                reqst.setBody('{"apikey": "'+MCDtls.API_Key__c+'","cid":"'+strCmpgn+'"}');        
                HttpResponse res = h.send(reqst);        
                system.debug(':: Response for getting  campaign open list:: ********'+res.getbody());
                setEmlAddrss = new Set<String>(); 
                JSONParser parser = JSON.createParser(res.getBody());
                while (parser.nextToken() != null) {
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)&& (parser.getText() == 'Email')) {
                        parser.nextToken();                     
                        setEmlAddrss.add(parser.getText());
                    } }
                mapCmpgnCndt.put(strCmpgn,setEmlAddrss); }      
        upsrtMCCndtLst(mapCmpgnCndt);       
        sendEmail(mapCmpgnCndt); }             
    public static void upsrtMCCndtLst(Map<String, Set<String>> mapCndtCmpgn)
    {
        Set<String> setAllEmlAddrss;
        Set<String> setExstngEmlAddrss;
        List<MCCandidateList__c> lstToUpdate = new List<MCCandidateList__c>();
        List<MCCandidateList__c> lstToUpsert = new List<MCCandidateList__c>();
        System.debug('Map Size******************'+mapCndtCmpgn.KeySet());
        for(String str : mapCndtCmpgn.KeySet())
        {
            setAllEmlAddrss = new Set<String>();
            setExstngEmlAddrss = new Set<String>();
            lstToUpdate = [Select Id, Campaign_Id__c, Candidate_Email__c, IsNew__c from MCCandidateList__c 
                                    where (Campaign_Id__c = : str) AND (Candidate_Email__c IN : mapCndtCmpgn.get(str))];
            setAllEmlAddrss = mapCndtCmpgn.get(str);
            for(MCCandidateList__c objCndt : lstToUpdate ) {
                setExstngEmlAddrss.add(objCndt.Candidate_Email__c); 
            }
            if(setExstngEmlAddrss.size() != 0 || !setExstngEmlAddrss.isEmpty()) {
                setAllEmlAddrss.removeAll(setExstngEmlAddrss);
            }
            for(String strNwEmlAddrss : setAllEmlAddrss)
            {           
                MCCandidateList__c objToInsrt= new MCCandidateList__c();
                objToInsrt.Campaign_Id__c = str;
                objToInsrt.Campaign_Name__c = mapCmpgnIdNme.get(str);
                lstToUpsert.add(objToInsrt); }
            for(MCCandidateList__c obj: lstToUpdate)
            {
                MCCandidateList__c updtCndt = new MCCandidateList__c(Id = obj.Id);
                updtCndt.IsNew__c = False;
                lstToUpsert.add(updtCndt);
            }
          }
        upsert lstToUpsert; }
    private static string createEmailBody(List<MCCandidateList__c> lstCmpgnMails)
    {
        //logic building an email
        return strHtmlBody;
    }
    private static void sendEmail(Map<String, Set<String>> mapCmpgnIdSet)
    {
        //list of email ids 
    }
 public static void getMCCandUnsubscribesList( string campId)    
    {  
        MCDtls = new Mailchimp_Details__c();
        //mapCmpgnCndt = new Map<String, Set<String>>();
        MCDtls = EZRE_Data_Utility.getMCDtls('MCAccount');       
        Http h = new Http();        
        HttpRequest reqst = new HttpRequest();  
        reqst.setMethod('POST');
        reqst.setBody('{"apikey": "'+MCDtls.API_Key__c+'","cid":"'+campId+'"}');        
        reqst.setEndpoint('https://'+MCDtls.Domain_Name__c+'.api.mailchimp.com/2.0/reports/unsubscribes.JSON');
            if(!Test.isRunningTest()) {       
                HttpResponse res = h.send(reqst);       
                JSONParser parser = JSON.createParser(res.getBody());
                while (parser.nextToken() != null) {
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)&& (parser.getText() == 'Email')) {
                        parser.nextToken();                     
                        setEmlAddrss.add(parser.getText()); }}}}
    public static void getMCCandBounceMessageList( string campId)    { 
        MCDtls = new Mailchimp_Details__c();
        //mapCmpgnCndt = new Map<String, Set<String>>();
        MCDtls = EZRE_Data_Utility.getMCDtls('MCAccount');       
        Http h = new Http();        
        HttpRequest reqst = new HttpRequest();  
        reqst.setMethod('POST');
        reqst.setBody('{"apikey": "'+MCDtls.API_Key__c+'","cid":"'+campId+'"}');        
        reqst.setEndpoint('https://'+MCDtls.Domain_Name__c+'.api.mailchimp.com/2.0/reports/bounce-messages.JSON');       
                HttpResponse res = h.send(reqst);        
                JSONParser parser = JSON.createParser(res.getBody());
                while (parser.nextToken() != null) {
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)&& (parser.getText() == 'Email')) {
                        parser.nextToken();                     
                        setBouncedEmlAddrss.add(parser.getText()); } } } 
    public static void updateUnsubCand() {
        list<candidate__c> upcandUnsub = new list<candidate__c>();
        list<candidate__c> lstcand = [select id,Name,Email__c,email_status__c from candidate__c where Email__c IN: setEmlAddrss];
               system.debug('canidateemailmatching list:: ********'+lstcand);
               if(lstcand.size()>0){
                   for(candidate__c Finalcandlist :lstcand) {
                       Finalcandlist.email_status__c = 'Unsubscribed';
                       upcandUnsub.add(Finalcandlist);}
                   update upcandUnsub;} }
    public static void updateBouncedCand()
    {
        list<candidate__c> upcandBounced = new list<candidate__c>();
        list<candidate__c> lstcand = [select id,Name,Email__c,email_status__c from candidate__c where Email__c IN: setBouncedEmlAddrss];
               system.debug('canidateemailmatching list:: ********'+lstcand);
               if(lstcand.size()>0){
                   for(candidate__c Finalcandlist :lstcand){
                       Finalcandlist.email_status__c = 'Bounced';
                       upcandBounced.add(Finalcandlist);}
                   update upcandBounced; } } }


any help will be high appreciable 
thank you so much guys in advance
  • February 02, 2015
  • Like
  • 0
Hii Friends

I am not familiar  at writing test clas i got arequirement
so please kindly  help me in writing this test class

this  is my class



global with sharing class EFAjaxRemotingFunctionsController
{
public EFAjaxRemotingFunctionsController(){}
public EFAjaxRemotingFunctionsController(ApexPages.StandardController controller){

    }

/* Object used to populate reference to user */
public EF_Request__c EFRequest
{
get;
set;
}

@RemoteAction
global static String getUserData(String recordId)
{
List<User> user = [select FirstName, LastName, Title, CompanyName from User where Id = : recordId];
// These methods are for serializing  Apex objects into JSON format available since Winter’12 release

String JSONString = JSON.serialize(user);
//Depends on your needs and way you want to format your result. Lets just hardcode the status value for now.
return '{"data":' +JSONString+', "error": "null", "status":"SUCCESS"}';
}
}
Thanks in Advance I am so kind of u
  • March 13, 2014
  • Like
  • 0
Hii Friends

I am not familiar  at writing test clas i got arequirement
so please kindly  help me in writing this test class

this  is my class 

public class EF_Approval_Utility {
  public static string currentuser;
  public EF_Requested__c efreq = new EF_Requested__c();
  public List<EF_Request_Approve_Controller.EF_ApprovalHistory> lstApprovalHistory {get;set;}
  public EF_Approval_Utility()
  {
   
  }
  public void captureApprovalHistory(List<EF_Request_Approve_Controller.EF_ApprovalHistory> approvalHistory, String Id)
  {
    try
    {
    String historyfield='';
    for(EF_Request_Approve_Controller.EF_ApprovalHistory ah:approvalHistory)
    {
       String s = '';
       s = ah.CreatedDate +''+ah.AssignedTo+''+ah.RequestorComments+ah.ApprovedRejectedBy+ah.ApproverComments;
      historyfield = historyfield+s;
    }
    efreq = [Select Approval_Comments__c from EF_Requested__c where Id=:Id];
    efreq.Approval_Comments__c=historyfield;
    update efreq;
    }catch(Exception e)
    {
      Apexpages.addMessages(e);
    }
  }
}




Thanks in advance 
  • March 13, 2014
  • Like
  • 1
Hii Friends

I am not familiar  at writing test clas i got arequirement 
so please kindly  help me in writing this test class 


Thanks in advance 



public class EF_Updateabc
{
    public EF_Updateabc()
    {
        UpdateEFKotaQueue();
    }
    public void UpdateEFKotaQueue()
    {
        List<string> lstEF_abc_QueueID = new List<string>();
        /*string strQuery =  EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Type__c + ' ' + EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Fields__c +
                           EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Relationship_fields__c + ' from ' +  EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Object__c +
                           ' where ' + EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Filter__c;
        system.debug('strQuery strQuery strQuery ::' + strQuery );
        List <EF_abc_Queue__c> lstEFabc_Queue_QueryData = Database.Query(strQuery);*/
      
        List <EF_abc_Queue__c> lstEFabc_Queue_QueryData = [SELECT Id, status__c, EF_Requested_Resource__c, abc_JSON__c,abc_Response__c, number_tried__c, EF_Requested_Resource__r.EF_Resource_Metadata__r.abc_App_ID__c, EF_Requested_Resource__r.EF_Request_ID__r.User_Name__r.abc_Id__c, EF_Requested_Resource__r.Request_Type__c from EF_abc_Queue__c where status__c='Request Sent' and number_tried__c<10 limit 10];
        system.debug('lstEFabc_Queue_QueryDatalstEFabc_Queue_QueryData::' + lstEFabc_Queue_QueryData);
       
        for(EF_abc_Queue__c objEF_abc_Queue_Local : lstEFabc_Queue_QueryData)
        {
            lstEF_abc_QueueID.add(objEF_abc_Queue_Local.Id);
        }
      
        if(lstEF_abc_QueueID.size()>0)
        {
            list<EF_abc_Queue__c> lstEfabctoUpdate = new list<EF_abc_Queue__c>();
            for(EF_abc_Queue__c oQueue: [select id, EF_Requested_Resource__r.EF_Request_ID__r.abc_Id__c,
                            EF_Requested_Resource__r.EF_Request_ID__r.User_Name__r.abc_Id__c,
                            abc_JSON__c, number_tried__c, EF_Requested_Resource__r.Request_Type__c,
                            EF_Requested_Resource__r.EF_Resource_Metadata__r.abc_App_ID__c, Status__c
                            from EF_abc_Queue__c
                            where id in : lstEF_abc_QueueID])
            {
                string userID = oQueue.EF_Requested_Resource__r.EF_Request_ID__r.abc_Id__c!=''?
                                oQueue.EF_Requested_Resource__r.EF_Request_ID__r.abc_Id__c:oQueue.EF_Requested_Resource__r.EF_Request_ID__r.User_Name__r.abc_Id__c;

                string appID = oQueue.EF_Requested_Resource__r.EF_Resource_Metadata__r.abc_App_ID__c;
              
                string strURLEnd = abc_EndPoint__c.getValues('abc').Site_URL__c;
                strURLEnd = strURLEnd + '/apps/' + appID + '/users/' + userID;
              
                String result     = '[]';
                String authToken    = abc_EndPoint__c.getValues('abc').Auth_token__c;
                Http h = new Http();
                HttpRequest req   = new HttpRequest();
                req.setEndpoint(strURLEnd);
                req.setMethod('GET');
                req.setHeader('Accept', 'application/json');
                req.setHeader('Authorization', authToken);
              
                HttpResponse res = h.send(req);
              
                if (200 == res.getStatusCode())
                {
                    result = res.getBody();
                    map<string, Object> mapDataToUpdate = (map<string, Object>)JSON.deserializeUntyped(result);
                  
                    if(mapDataToUpdate.get('status') == 'Completed')
                    {
                        oQueue.Status__c = 'Complete';
                        lstEfabctoUpdate.add(oQueue);
                    }
                }
            }
          
            if(lstEfabctoUpdate.size()>0)
            {
                try{update lstEfabctoUpdate;}
                catch(Exception ex){EF_Error_Log.logException('EF_abc_Queue', lstEfabctoUpdate, 'DML', 'HIGH', ex.getMessage());
                }
            }
        }
    }
  • March 12, 2014
  • Like
  • 0
Hii Friends

I am not familiar  at writing test clas i got arequirement
so please kindly  help me in writing this test class

this  is my class 

public class EF_Approval_Utility {
  public static string currentuser;
  public EF_Requested__c efreq = new EF_Requested__c();
  public List<EF_Request_Approve_Controller.EF_ApprovalHistory> lstApprovalHistory {get;set;}
  public EF_Approval_Utility()
  {
   
  }
  public void captureApprovalHistory(List<EF_Request_Approve_Controller.EF_ApprovalHistory> approvalHistory, String Id)
  {
    try
    {
    String historyfield='';
    for(EF_Request_Approve_Controller.EF_ApprovalHistory ah:approvalHistory)
    {
       String s = '';
       s = ah.CreatedDate +''+ah.AssignedTo+''+ah.RequestorComments+ah.ApprovedRejectedBy+ah.ApproverComments;
      historyfield = historyfield+s;
    }
    efreq = [Select Approval_Comments__c from EF_Requested__c where Id=:Id];
    efreq.Approval_Comments__c=historyfield;
    update efreq;
    }catch(Exception e)
    {
      Apexpages.addMessages(e);
    }
  }
}




Thanks in advance 
  • March 13, 2014
  • Like
  • 1
Hii Friends

I am not familiar  at writing test clas i got arequirement
so please kindly  help me in writing this test class

this  is my class



global with sharing class EFAjaxRemotingFunctionsController
{
public EFAjaxRemotingFunctionsController(){}
public EFAjaxRemotingFunctionsController(ApexPages.StandardController controller){

    }

/* Object used to populate reference to user */
public EF_Request__c EFRequest
{
get;
set;
}

@RemoteAction
global static String getUserData(String recordId)
{
List<User> user = [select FirstName, LastName, Title, CompanyName from User where Id = : recordId];
// These methods are for serializing  Apex objects into JSON format available since Winter’12 release

String JSONString = JSON.serialize(user);
//Depends on your needs and way you want to format your result. Lets just hardcode the status value for now.
return '{"data":' +JSONString+', "error": "null", "status":"SUCCESS"}';
}
}
Thanks in Advance I am so kind of u
  • March 13, 2014
  • Like
  • 0
Hii Friends

I am not familiar  at writing test clas i got arequirement 
so please kindly  help me in writing this test class 


Thanks in advance 



public class EF_Updateabc
{
    public EF_Updateabc()
    {
        UpdateEFKotaQueue();
    }
    public void UpdateEFKotaQueue()
    {
        List<string> lstEF_abc_QueueID = new List<string>();
        /*string strQuery =  EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Type__c + ' ' + EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Fields__c +
                           EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Relationship_fields__c + ' from ' +  EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Object__c +
                           ' where ' + EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Filter__c;
        system.debug('strQuery strQuery strQuery ::' + strQuery );
        List <EF_abc_Queue__c> lstEFabc_Queue_QueryData = Database.Query(strQuery);*/
      
        List <EF_abc_Queue__c> lstEFabc_Queue_QueryData = [SELECT Id, status__c, EF_Requested_Resource__c, abc_JSON__c,abc_Response__c, number_tried__c, EF_Requested_Resource__r.EF_Resource_Metadata__r.abc_App_ID__c, EF_Requested_Resource__r.EF_Request_ID__r.User_Name__r.abc_Id__c, EF_Requested_Resource__r.Request_Type__c from EF_abc_Queue__c where status__c='Request Sent' and number_tried__c<10 limit 10];
        system.debug('lstEFabc_Queue_QueryDatalstEFabc_Queue_QueryData::' + lstEFabc_Queue_QueryData);
       
        for(EF_abc_Queue__c objEF_abc_Queue_Local : lstEFabc_Queue_QueryData)
        {
            lstEF_abc_QueueID.add(objEF_abc_Queue_Local.Id);
        }
      
        if(lstEF_abc_QueueID.size()>0)
        {
            list<EF_abc_Queue__c> lstEfabctoUpdate = new list<EF_abc_Queue__c>();
            for(EF_abc_Queue__c oQueue: [select id, EF_Requested_Resource__r.EF_Request_ID__r.abc_Id__c,
                            EF_Requested_Resource__r.EF_Request_ID__r.User_Name__r.abc_Id__c,
                            abc_JSON__c, number_tried__c, EF_Requested_Resource__r.Request_Type__c,
                            EF_Requested_Resource__r.EF_Resource_Metadata__r.abc_App_ID__c, Status__c
                            from EF_abc_Queue__c
                            where id in : lstEF_abc_QueueID])
            {
                string userID = oQueue.EF_Requested_Resource__r.EF_Request_ID__r.abc_Id__c!=''?
                                oQueue.EF_Requested_Resource__r.EF_Request_ID__r.abc_Id__c:oQueue.EF_Requested_Resource__r.EF_Request_ID__r.User_Name__r.abc_Id__c;

                string appID = oQueue.EF_Requested_Resource__r.EF_Resource_Metadata__r.abc_App_ID__c;
              
                string strURLEnd = abc_EndPoint__c.getValues('abc').Site_URL__c;
                strURLEnd = strURLEnd + '/apps/' + appID + '/users/' + userID;
              
                String result     = '[]';
                String authToken    = abc_EndPoint__c.getValues('abc').Auth_token__c;
                Http h = new Http();
                HttpRequest req   = new HttpRequest();
                req.setEndpoint(strURLEnd);
                req.setMethod('GET');
                req.setHeader('Accept', 'application/json');
                req.setHeader('Authorization', authToken);
              
                HttpResponse res = h.send(req);
              
                if (200 == res.getStatusCode())
                {
                    result = res.getBody();
                    map<string, Object> mapDataToUpdate = (map<string, Object>)JSON.deserializeUntyped(result);
                  
                    if(mapDataToUpdate.get('status') == 'Completed')
                    {
                        oQueue.Status__c = 'Complete';
                        lstEfabctoUpdate.add(oQueue);
                    }
                }
            }
          
            if(lstEfabctoUpdate.size()>0)
            {
                try{update lstEfabctoUpdate;}
                catch(Exception ex){EF_Error_Log.logException('EF_abc_Queue', lstEfabctoUpdate, 'DML', 'HIGH', ex.getMessage());
                }
            }
        }
    }
  • March 12, 2014
  • Like
  • 0