• Eric Pepin NH
  • NEWBIE
  • 5 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 6
    Replies
I;m new to coding and cannot figure out the issue with my test class. Can someone please help!

This is the trigger I am testing:

trigger CreateProProv on OpportunityLineItem (after update){
    //Instantiate the list here, before the loop
    List<Pro_Provisioning__c> myList = new List<Pro_Provisioning__c>();
    for (OpportunityLineItem OppLI : Trigger.new) {
        if (OppLI.Oppp_is_signed__c == 'Signed' && OppLI.Oppp_is_signed__c!= trigger.OldMap.get(OppLI.Id).Oppp_is_signed__c  
        && OppLI.Product_Family_for_Rollups__c == 'Pro'&& OppLI.Product_Subfamily_for_Rollups__c != 'Legacy' ) {
            Pro_Provisioning__c PP = new Pro_Provisioning__c();
            PP.Related_Opportunity__c = OppLI.OpportunityID;
            PP.OpLI_ID__c = OppLI.id;
            PP.Product1__c = OppLI.Product_Name_for_Formulas__c;
            PP.CurrencyIsoCode= OppLI.CurrencyIsoCode;
            PP.Pro_Experiments_Allowedt__c= OppLI.Pro_Experiments_Allowed__c;
            PP.Pro_Experiments_Periodt__c= OppLI.Pro_Experiments_Period__c;
            PP.Language__c = OppLI.Pro_Language__c;
            //Put the new record inside the list
            myList.add(PP);
        }
    }
    //Insert the whole list once the loop is finished (outside the loop)
    insert myList;
}

This is my test class:
@isTest public Class CreateProProvTest{
  @istest private static void testCreateProProvTrigger(){
Product2 prod = new Product2(Name = 'test', Family = 'Pro');
insert prod;
Id pricebookId = Test.getStandardPricebookId();
PricebookEntry standardPrice = new PricebookEntry(Pricebook2Id = pricebookId, Product2Id = prod.Id, UnitPrice = 500, IsActive = true);
insert standardPrice;
Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
insert customPB;
PricebookEntry customPrice = new PricebookEntry(Pricebook2Id = customPB.Id, Product2Id = prod.Id, UnitPrice = 500, IsActive = true);
insert customPrice;
Account acc = new Account(Name='TestAccount');
insert acc;
Opportunity opp = new Opportunity(Name='TestOpportunity', AccountId=acc.Id, CloseDate=Date.Today(), 
                                  StageName='Qualification', Pricebook2Id=customPB.Id);
insert opp;
OpportunityLineItem oli = new OpportunityLineItem(OpportunityId = opp.Id, Quantity = 1, TotalPrice = 500, 
                                                  Oppp_is_signed__c = 'Not Signed', Pro_Experiments_Allowed__c = 3, 
                                                  Pro_Experiments_Period__c = 'Monthly', PricebookEntryId=customPrice.Id);
insert oli;
Test.startTest();
      oli.Oppp_is_signed__c = 'Signed';
          Update oli;
test.stopTest();
}
}

On the trigger record in SF Salesforce tells me that I have 100% test coverage for the trigger, but when I try to validate in my QA sandbox using run specified tests (this test only) the system throws an error and says "

Code Coverage Warning
Your code coverage is 35%. You need at least 75% coverage to complete this deployment.
CreateProProv"

Can someone please help! What am I missing?

Cheers!!

Theo

 
Hi, 

I have to figure out why this code does not entirely work. 

The opportunity and the related contact roles are being created fine however, the Competitions object is not being created as a related list to the opportunity.

I have been debugging with alerts (I know its not ideal but i have no expertrise in JS!) and i can see that all is working as expected, however this line at the end of the codeis not successful.

result = sforce.connection.create(newCompetitions); 

I have been trying to debug with a SF debug log but I see nothing. Is there anyway I can see the error related to this line and see why it's not doing as expected?

Alternatively, can you spot if the code is incorrectly formulated?

Thanks so much!

Belen


{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")}

var newOpportunity = new sforce.SObject("Opportunity");
newOpportunity.AccountId =  '{!Opportunity.AccountId}';
newOpportunity.LeadEventName__c = '{!JSENCODE(Opportunity.LeadEventName__c)}';
newOpportunity.Recurrence__c = '{!JSENCODE(TEXT(Opportunity.Recurrence__c))}';
newOpportunity.RecordTypeId = '{!Opportunity.RecordTypeId}';
newOpportunity.LeadEventType__c = '{!JSENCODE(TEXT(Opportunity.LeadEventType__c))}';
newOpportunity.EventIndustry__c = '{!JSENCODE(TEXT(Opportunity.EventIndustry__c))}';
newOpportunity.CloseDate = new Date();
newOpportunity.Name = '{!JSENCODE(Opportunity.Name)}';
newOpportunity.StageName = 'Future Opportunity';
newOpportunity.EventDescription_del__c = '{!Opportunity.EventDescription_del__c}'; 
newOpportunity.Industry_Subtype__c = '{!Opportunity.Industry_Subtype__c}'; 
newOpportunity.BESydneyTeam__c = '{!Opportunity.BESydneyTeam__c}'; 
newOpportunity.Delegate_Profile__c = '{!Opportunity.Delegate_Profile__c}'; 
newOpportunity.Past_Registration_Fees__c ='{!Opportunity.Past_Registration_Fees__c}'; 
var result = sforce.connection.create([newOpportunity]);

var newOpportunityId;
if (result[0].getBoolean("success")) {
   newOpportunityId = result[0].id;
}
else {
   alert('Unable to clone Opportunity.');
}

if (newOpportunityId) {
   //Clone Opportunity Contact Roles
   var opportunityContactRolesQuery = sforce.connection.query("" +
      "Select ContactId, Role, IsPrimary " +
      "From OpportunityContactRole " +
      "Where OpportunityId = '{!Opportunity.Id}'");

   var opportunityContactRoles = opportunityContactRolesQuery.getArray("records");
   var newOpportunityContactRoles = [];
   var newOpportunityContactRole;
   for (var counter = 0; counter < opportunityContactRoles.length; counter++) {
      newOpportunityContactRole = new sforce.SObject("OpportunityContactRole");
      newOpportunityContactRole.ContactId = opportunityContactRoles[counter].ContactId;
      newOpportunityContactRole.IsPrimary = opportunityContactRoles[counter].IsPrimary;
      newOpportunityContactRole.Role = opportunityContactRoles[counter].Role;
      newOpportunityContactRole.OpportunityId = newOpportunityId;
      newOpportunityContactRoles.push(newOpportunityContactRole);
   }
   if(newOpportunityContactRoles.length > 0) {
      result = sforce.connection.create(newOpportunityContactRoles);
   }

   //Clone Competitions
   var competitionQuery = sforce.connection.query("" +
      "Select City__c, DelegatesAttended__c, DestinationOffers__c, EventHeldYear__c, KeyLearnings__c, Strength_of_Competitor_Bid__c, Weakness_of_Competitor_Bid__c, WinningCity__c, RecordTypeId, RecordType.DeveloperName " +
      "From Competition_Event_History__c " +
      "Where Opportunity__c = '{!Opportunity.Id}'");
   
   var competitions = competitionQuery.getArray("records");
   var newCompetitions = [];
   var newCompetition;
   for (var counter = 0; counter < competitions.length; counter++) {
      if (competitions[counter].RecordType.DeveloperName == 'Historical_Destination') {
         newCompetition = new sforce.SObject("Competition_Event_History__c");
         newCompetition.City__c = competitions[counter].City__c;
         newCompetition.DelegatesAttended__c = competitions[counter].DelegatesAttended__c;
         newCompetition.DestinationOffers__c = competitions[counter].DestinationOffers__c;
         newCompetition.EventHeldYear__c = competitions[counter].EventHeldYear__c;
         newCompetition.KeyLearnings__c = competitions[counter].KeyLearnings__c;
         newCompetition.Strength_of_Competitor_Bid__c = competitions[counter].Strength_of_Competitor_Bid__c;
         newCompetition.Weakness_of_Competitor_Bid__c = competitions[counter].Weakness_of_Competitor_Bid__c;
         newCompetition.WinningCity__c = competitions[counter].WinningCity__c;
         newCompetition.RecordTypeId = competitions[counter].RecordTypeId;
         newCompetition.Opportunity__c = newOpportunityId;
         newCompetitions.push(newCompetition);
      }
   }
   if (newCompetitions.length > 0) {
      result = sforce.connection.create(newCompetitions);
   }
   window.location.href = '/' + newOpportunityId;
}

 
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;
    }
}
  @AuraEnabled
    public static List <User> fetchSearchQueueUser(String SearchUserKeyword, String grpId) {
        try{
            string searchkey = '%'+ SearchUserKeyword + '%';
            List <User> returnList = new List <User> ();
            List <User> lstOfUser;
            String sortField ;
            boolean isAsc;
            List <String> lstOfSubGroup= new List <String> ();
            List <String> lstOfUserIds = new List <String> ();
            set <String> lstOfGrpIds = new set <String> ();
            List <GroupMember> lstOfGroupMember;
            List <GroupMember> lstOfSubGroupMember;
            Set<id> idGroup = new Set<id>();
            //To get subgroup:
            lstOfSubGroupMember =  [SELECT UserOrGroupId,Group.Name from GroupMember WHERE GroupId=: grpId LIMIT 500];
            for(GroupMember gm : lstOfSubGroupMember){
                if(String.Valueof(gm.UserOrGroupId).startsWith('00G')){
                    idGroup.add(gm.UserOrGroupId);
                }
            }
            lstOfGroupMember =  [SELECT Id,UserOrGroupId,GroupId from GroupMember WHERE GroupId  IN: idGroup LIMIT 500];
            for(GroupMember gm : lstOfGroupMember){
                lstOfUserIds.add(gm.UserOrGroupId);
            }
            system.debug(searchkey);
            if(string.isBlank(searchKey)){
              lstOfUser = [select id,name,federationIdentifier,userrole.name,Manager.name,profile.name from user where Id IN: lstOfUserIds and profile.name in ('Service Agent','Work Order Approver') order by name asc LIMIT 500];
                if (sortField != '') {
                     lstOfUser += ' order by ' + sortField; ---------------------------------------------------->error
                  // if isAsc is equal tp ture then set 'asc' order otherwise set 'desc' order.
                 if (isAsc) {
                    lstOfUser += ' asc';                            ---------------------------------------------------->error
                 } else {
                    lstOfUser += ' desc';                          ---------------------------------------------------->error
         }
      }
            }
            else{
                    lstOfUser = [select id,name, federationIdentifier,userrole.name,Manager.name,profile.name from user where Id IN: lstOfUserIds and (federationIdentifier like: searchkey or name like: searchkey)  and profile.name in ('Service Agent','Work Order Approver') order by name asc LIMIT 500];        
                
            }
            system.debug(lstOfUser);     
            return lstOfUser;
        }
        catch(Exception e)
        {
            System.debug('The following exception has occurred: ' + e.getMessage());
            return null;
        }
  1.     }