• Abiola Enifeni 23
  • NEWBIE
  • 0 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 0
    Replies
Hi Guys, 

Please could someone be so kind to help me with the Test Class to the Apex Trigger below;
 APEX TRIGGER:
Trigger SOSPCall_Counter on Task (after insert) {  
Set<Id> setClosedTaskAccountIds = new Set<Id>();
List<Account> listAccountUpdate = new List<Account>();
List<Account> listClosedTaskAccounts = new List<Account>();
List<Account> listUpdatedTaskAccounts = new List<Account>();
List<Account> listUpdatedAccounts = new List<Account>();

if(Trigger.IsAfter){
    if(Trigger.IsInsert  || Trigger.isUpdate) {
        for(Task t: Trigger.new) {
            if(String.valueOf(t.WhatId).startsWithIgnoreCase('001')) {
                if(t.Status.equalsIgnoreCase('Completed')){
                    setClosedTaskAccountIds.add(t.WhatId);
                    System.debug('@@@@Inside Completed@@@'+setClosedTaskAccountIds);
                }
               
                if(Trigger.IsUpdate){
                    if(Trigger.oldMap.get(t.Id).WhatId != t.WhatId){
                        if(t.Status.equalsIgnoreCase('Completed')){
                            
                            setClosedTaskAccountIds.add(Trigger.oldMap.get(t.Id).WhatId );
                            System.debug('@@@Inside Update Closed@@@'+setClosedTaskAccountIds);
                        }
                        
                    }
                }
            }
        }
    }
    
    
         
    listClosedTaskAccounts =[SELECT Id, Left_Message__c, RecordTypeId, Patient_Status__c,(Select Status From Tasks Where Status = 'Completed' AND Call_Reason__c = 'Left Message' )  
                             FROM Account 
                             WHERE Id =:setClosedTaskAccountIds
                             AND Patient_Status__c = 'Eligible'];

    System.debug('@@@@ListClosedTaskAccounts'+listClosedTaskAccounts );

    try{
        System.debug('@@@@listAccountUpdate'+listAccountUpdate);
        update listAccountUpdate;
    }catch(System.Exception e){
        System.debug('@@@error'+e.getMessage());
    }
    
    
     listUpdatedTaskAccounts =[SELECT Id, Left_Message__c, RecordTypeId, Eligibility_Date__c,Patient_Status__c, (Select Status From Tasks Where Status = 'Completed' AND Call_Reason__c = 'Left Message' )  
                             FROM Account 
                             WHERE Id =:setClosedTaskAccountIds
                             ];
    
    
    for(Account a : listUpdatedTaskAccounts)        
    {
     List<Task> ltsk = a.Tasks;
        if ((a.Left_Message__c <= 2) && (a.Patient_Status__c == 'Eligible'))  {
            a.Left_Message__c = a.Left_Message__c + 1;
            system.debug('ltsk.size()  line 67 ' + ltsk.size());
            system.debug('a.Patient_Status__c  line 68 ' + a.Patient_Status__c);
            system.debug('a.Left_Message__c    line 69 ' + a.Left_Message__c);
        }
        if ((a.Left_Message__c > 2) && (a.Patient_Status__c == 'Eligible'))  {
            a.Left_Message__c = 0;
            a.Patient_Status__c = 'Non-Responsive Member';
            system.debug('ltsk.size()  line 74 ' + ltsk.size());
            system.debug('a.Patient_Status__c  line 75 ' + a.Patient_Status__c);
            system.debug('a.Left_Message__c    line 76 ' + a.Left_Message__c);
        }
    update listUpdatedTaskAccounts;
    System.debug('***LOOK MA WE MADE IT***Update happened');
          
}


}

TEST CLASS
@isTest
private class SOSPCall_CounterTest{
    
  @isTest
  static void setupTestData(){
    Account acc = new Account(LastName = 'LastName870', Patient_Status__c = 'Eligible');
    Insert acc; 
      
    Task tsk = new Task(Status = 'Completed', Call_Reason__c = 'Left Message', Subject = 'This is a Test', WhatId = acc.Id);
    Insert tsk;  

  }
  static testMethod void test_TaskTrigger(){
   test.startTest();
    List<Account> account1_Obj  =  [SELECT Id,LastName,Patient_Status__c,Left_Message__c from Account];
    System.assertEquals(1,account1_Obj.size());  
    Task task_Obj = new Task(Status = 'Completed', Subject = 'This is a Test', Call_Reason__c = 'Left Message');
    Insert task_Obj; 
   test.stopTest();
  }
}

for some reasons oblivious to me. the Test Class is not working.
public with sharing class myLeadToursController 
{
   @AuraEnabled public User u {get;set;}    
   @AuraEnabled    
   public static String getLeadTour(Id objectId)
   {
     system.debug('objectId : '+objectId);
      List<Lead> leadtourList = [SELECT Id, 
                                       VOICE_LEAD_ID__c                                                                             
                                       FROM Lead WHERE Id=:objectId] ;  
       
       String vcId = leadtourList[0].VOICE_LEAD_ID__c;
       String body =JSON.Serialize( '{"leadId" : "'+ vcId +'"}');
       String httpVerb = 'POST';
       system.debug(body);
      
         ServiceMarketingJson ws = new ServiceMarketingJson();
            //Convert voice lead id to long to call tours web service
            Long voiceLeadIDNumber = long.valueOf(vcId);
       
            ServiceMarketingRequests.GetLeadInfoRequest myrequest = new ServiceMarketingRequests.GetLeadInfoRequest(voiceLeadIDNumber);
            
             list<ServiceMarketingJSONObjects.LeadTour> leadTourResponse  = new list<ServiceMarketingJSONObjects.LeadTour>();
            String serviceMethod = 'GetLeadTours';                         
            String jsonResponse = SendJSONRequest(httpVerb, JSON.serialize(myRequest), serviceMethod);
                 
       
       if (!test.isRunningTest()) {
                try {
                    jsonResponse =SendJSONRequest(httpVerb, JSON.serialize(myRequest), serviceMethod);
                }
                catch(Exception e) {
                    if(u.Business_Unit__c != null && u.Business_Unit__c == 'VIP Reservations') {
                        //send the error email to the dev team
                        Error_Email.sendErrorEmail('VIPRes - myLeadToursController', 'myLeadToursController (constructor - GetLeadTours)', System.UserInfo.getName(), e.getMessage());
                        //log the error in SFDC
                        Error_Exception.logException('VIPRes - myLeadToursController', 'myLeadToursController (constructor - GetLeadTours)', System.UserInfo.getUserId(), e);
                    } else {
                        Error_Exception.logException('myLeadToursController', 'myLeadToursController (constructor - GetLeadTours)', System.UserInfo.getUserId(), e);
                    }
                }

            } else {
                jsonResponse = '[{"ConfirmationStatus":4,"HasSales":false,"LeadId":1474999137,"ManifestCode":"39","ManifestDescription":"LV BLVD - TOWER 1","Office":39,"OfficeDescription":"LVB Action Line","Status":8,"StatusDescription":"CANCELLED","TourBooked":"/Date(-62135578800000-0500)/","TourDate":"/Date(1465444800000-0400)/","TourSeq":1,"TourTime":"","TourWave":12,"TourWaveDescription":"2:00 PM","Type":3,"TypeDescription":"VIP TOUR","UnicaCampaignCode":null,"UnicaHumanId":0,"UnicaLocationId":0,"UnicaOfferCode":null,"UnicaTreatmentCode":null,"UnicaWebServiceName":null,"UnicaXmlMetaData":null,"WasUpdated":false}]';
                
            }

         if (jsonResponse != null && jsonResponse.length() != 0) 
         {
                leadTourResponse = ServiceMarketingJSONObjects.parseLeadTours(jsonResponse); 
             Integer tourCounter = 0; 
         }
       system.debug(leadTourResponse);
      return jsonResponse;                                    
   }
    
    
   @AuraEnabled 
   public static String getReservation(Id objectId)
   {      
      system.debug('objectId : '+objectId);
      List<Lead> reservationList = [SELECT Id, 
                                       VOICE_LEAD_ID__c                                                                             
                                       FROM Lead WHERE Id=:objectId] ;
                                       
        String resId = reservationList[0].VOICE_LEAD_ID__c;
        String body =JSON.Serialize( '{"leadId" : "'+ resId +'"}');
        String httpVerb = 'POST';                               
        ServiceMarketingJson ws = new ServiceMarketingJson();
        //Convert voice lead id to long to call res web service
        Long voiceLeadIDNumber = long.valueOf(resId);                               
            
         ServiceMarketingRequests.GetLeadInfoRequest myRequest = new ServiceMarketingRequests.GetLeadInfoRequest(voiceLeadIDNumber);
            
         
            
        ServiceMarketingGetResResponse.GetResResponseParent grResponse  = new ServiceMarketingGetResResponse.GetResResponseParent();
        String serviceMethod = 'GetReservation';                 
        String jsonResponse = SendJSONRequest(httpVerb, JSON.serialize(myRequest), serviceMethod);               
            
        if (jsonResponse != null && jsonResponse.length() != 0){           
            grResponse = ServiceMarketingGetResResponse.parseGetResResponseParent(jsonResponse);
             Integer resCounter = 0;            
        }          
        system.debug(grResponse);
                          
        return jsonResponse;  
          
   }
   
    
    @AuraEnabled
    public static string SendJSONRequest(String httpVerb, String body, String serviceMethod)
    {   
        HttpRequest req = new HttpRequest();
        req.setEndpoint(system.label.ESB_SvcMkt_BookTourFull + serviceMethod);
        req.setMethod(httpVerb);
        req.setTimeout(60000);
        req.setHeader('Content-Type', 'application/json;charset=utf-8');
        if(!test.isRunningTest())
        {
            req.setHeader('Authorization', ServiceAuthenticateJsonESB.GetAuthorizationBearer()); //'Bearer '+myTempToken);
        }
        else
        {
            req.setHeader('Authorization', 'Bearer 123NO'); //'Bearer '+myTempToken);
        }
        req.setBody(body);
        Http http = new Http();
        HTTPResponse res;
        String response;

        system.debug('Request Header: ' + req.getHeader('Content-Type'));
        system.debug('Request Header: ' + req.getHeader('Authorization'));
        system.debug('Request URL & Method: ' + req);
        system.debug('Request BODY: ' + req.getBody());

        if(!test.isRunningTest())
        {
            res = http.send(req);
            response = res.getbody();
            system.debug(res);
           // response = response.replace('\\','');
        }
        else
        {
            response = 'Nope, go away';
        }
        system.debug('Service URL: ' + req.getEndpoint());
        system.debug('BODY ' + req.getBody());
        system.debug('RESPONSE ' + response);
        system.debug('Auth Header: ' + req.getHeader('Authorization'));

        return response;
    }

    @AuraEnabled
    public static datetime convertEPOCHBackToDT(string str)
    {
        DateTime ret = null;
        if (str != null)
            ret = DateTime.newInstance(long.valueOf(str.substring(str.indexOf('(')+1, str.indexOf('-'))));
        return ret;
    }
}