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
pradeep kumar s 1pradeep kumar s 1 

SOAP API integration with batch apex and scheduler

friends,
i have written schedule apex for calling webservice every hour,batch apex is invoked inside the schedule apex.from this service response will be got and records are inserted from that response.i am using soap api webservice.now i am writing test classes for this.but iam getting  this error.
how can i fix it?
here is the error---
​'System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out '
PawanKumarPawanKumar
Hi Pradeep,

You just make sure, you are not doing any insert or update(DML operation) before web service test call. Otherwise you will get this error always.

e.g.

@isTest static void testBatchCallout() {
   My_Custom_Object__c foo = new My_Custom_Object__c(Name='test');
   insert foo;
// The above insert/update should notbe there before WS call.

   
   MyClient client = new MyClient();
   MyWSMock mywsMockImpl = new MyWSMock();
   Test.setMock(HttpCalloutMock.class,mywsMockImpl);

   Test.startTest();
   client.bar(foo.Id);
   Test.stopTest();
}


Workaround: You prepare all your test data inside testSetup() method in your test class.
e.g.

@testSetup 
static void methodName() {
  My_Custom_Object__c foo = new My_Custom_Object__c(Name='test');
   insert foo;
}

@isTest static void testBatchCallout() {
 
  // you query your created data in your test setup method here
  // the above query will give only data created in your test setup method(not all the data available in your salesforce instance)
  My_Custom_Object__c foo = [select Id,otherfield from My_Custom_Object__c ];
   
   MyClient client = new MyClient();
   MyWSMock mywsMockImpl = new MyWSMock();
   Test.setMock(HttpCalloutMock.class,mywsMockImpl);

   Test.startTest();
   client.bar(foo.Id);
   Test.stopTest();
}

Regards,
Pawan Kumar
pradeep kumar s 1pradeep kumar s 1
thanks Pawan for your reply,
i have checked and inserted some records in testsetup but still i am getting the same error and how can we pass id of that record,actually i have written batch apex and in execute method the webservice is called with a webservice method.
and the class which is generated by apex wsdl2 tool is not globally mentioned.i am calling that one locally and the method i.e webservice method needs some parameters those are given already inside the execute method only.so i can not pass parameters locally.
PawanKumarPawanKumar
Hi Pradeep,
Thanks for explanation.

If you can share your batch code then i can try to help you further.

Regards,
Pawan Kumar
pradeep kumar s 1pradeep kumar s 1
/* * */ global class TrackingStatus_BatchApex implements Database.Batchable,Database.AllowsCallouts{ /*start method of Batch Apex*/ global Database.QueryLocator start(Database.BatchableContext bc){ return Database.getQueryLocator('SELECT Id,TrackingNos__c from OrderDestination__c '); } /*execute method of Batch Apex */ global void execute(Database.BatchableContext bc,ListOrderDestinations){ List Shipment_Facts=new List(); List Travel_History=new List(); DateTime eventTimeStamp; /*TrackingNumbers are taken from OrderDestinations*/ Map TrackingNumbers=new Map(); for(OrderDestination__c O:OrderDestinations){ if(O.TrackingNos__c !=null) for(String S:O.TrackingNos__c.split(',')){ TrackingNumbers.put(S.trim(),O); } } /*Trackign No's are taken from Shipment Facts Travel History records mustbe taken per every timestamp */ Map Existing_Shipment_Facts=new Map (); Map> Existing_Travel_History_TimeStamps=new Map> (); for(Shipment_Facts__c S:[SELECT Id,(SELECT EventTimestamp__c FROM Travel_History__r),Delivery_Attempts__c,Delivery_Status__c,TrackingNumber__c From Shipment_Facts__c WHERE OrderDestination__c IN : OrderDestinations]){ Existing_Shipment_Facts.put(S.TrackingNumber__c,S); if(S.Travel_History__r!=null){ Set TimeStamps=new Set (); for(Travel_History__c T:S.Travel_History__r) if(T.EventTimestamp__c!=null) TimeStamps.add(T.EventTimestamp__c.format()); Existing_Travel_History_TimeStamps.put(S.TrackingNumber__c,TimeStamps); } } SYSTEM.DEBUG(Existing_Shipment_Facts); Map Old_Shipment_Facts=new Map(); Map New_Shipment_Facts=new Map(); Map Fedex_TrackReply=new Map(); Map> CompletedTrackDetails=new Map>(); Map> TrackDetails=new Map>(); Map> TrackEvents=new Map>(); Map> NewTravel_History=new Map> (); Map Individual_Track_Detail=new Map (); /*If Order Destnations don't have Shipment_Facts,new Shipment_Facts are created based on Tracking No's */ /*Input parameters should be passed i.e Developer Key,Developer Password,Account Number,Meter Number fedexComWsTrackV14 is generated from WSDL file This is hard coded */ fedexComWsTrackV14.WebAuthenticationCredential fedex=new fedexComWsTrackV14.WebAuthenticationCredential(); fedex.key=FedEx_Production_Integration__c.getValues('Bogle User1').Developer_Key__c; fedex.password=FedEx_Production_Integration__c.getValues('Bogle User1').Developer_Password__c; fedexComWsTrackV14.ClientDetail details=new fedexComWsTrackV14.ClientDetail(); details.AccountNumber=FedEx_Production_Integration__c.getValues('Bogle User1').Account_Number__c; details.MeterNumber=FedEx_Production_Integration__c.getValues('Bogle User1').Meter_Number__c; /*Value of CustomerTransactionId is taken from FeDex Documentation and this response is taken by track by no so 'Track By Number_v14' should be taken*/ fedexComWsTrackV14.TransactionDetail TransactionDetail=new fedexComWsTrackV14.TransactionDetail(); TransactionDetail.CustomerTransactionId='Track By Number_v14'; /*Version is taken from FeDex */ fedexComWsTrackV14.VersionId Version=new fedexComWsTrackV14.VersionId(); Version.ServiceId='trck'; Version.Major=14; Version.Intermediate=0; Version.Minor=0; List SelectionDetails=new List(); fedexComWsTrackV14.TrackSelectionDetail TrackSelectionDetail=new fedexComWsTrackV14.TrackSelectionDetail(); TrackSelectionDetail.CarrierCode='FDXE'; fedexComWsTrackV14.TrackPackageIdentifier PackageIdentifier=new fedexComWsTrackV14.TrackPackageIdentifier(); PackageIdentifier.Type_x='TRACKING_NUMBER_OR_DOORTAG'; String[] ProcessingOptions=new List{'INCLUDE_DETAILED_SCANS'}; fedexComWsTrackV14.Address Destination=new fedexComWsTrackV14.Address(); Destination.GeographicCoordinates='rates evertitque aequora'; TrackSelectionDetail.PackageIdentifier=PackageIdentifier; TrackSelectionDetail.Destination=Destination; SelectionDetails.add(TrackSelectionDetail); fedexComWsTrackV14.WebAuthenticationDetail WebAuthenticationDetail=new fedexComWsTrackV14.WebAuthenticationDetail(); WebAuthenticationDetail.UserCredential=fedex; fedexComWsTrackV14.TrackServicePort TrackServicePort=new fedexComWsTrackV14.TrackServicePort(); TrackServicePort.timeout_x=12000; if(!TrackingNumbers.isEmpty()) for(String S: TrackingNumbers.keySet()){ if(Existing_Shipment_Facts.containsKey(S)){ if(Existing_Shipment_Facts.get(S).Delivery_Status__c!='Delivered') { PackageIdentifier.Value=Existing_Shipment_Facts.get(S).TrackingNumber__c ; fedexComWsTrackV14.TrackReply TrackReply=new fedexComWsTrackV14.TrackReply(); TrackReply=TrackServicePort.track(WebAuthenticationDetail, Details, TransactionDetail, Version, SelectionDetails,10,ProcessingOptions); if(TrackReply!=null) Fedex_TrackReply.put(PackageIdentifier.Value,TrackReply); if(TrackReply.CompletedTrackDetails!=null) CompletedTrackDetails.put(PackageIdentifier.Value,TrackReply.CompletedTrackDetails); Old_Shipment_Facts.put(PackageIdentifier.Value,Existing_Shipment_Facts.get(S)); } }else{ //insert new Shipment_Facts__c(Delivery_Status__c='testing1'); PackageIdentifier.Value=S; fedexComWsTrackV14.TrackReply TrackReply=new fedexComWsTrackV14.TrackReply(); TrackReply=TrackServicePort.track(WebAuthenticationDetail, Details, TransactionDetail, Version, SelectionDetails,10,ProcessingOptions); if(TrackReply!=null) Fedex_TrackReply.put(PackageIdentifier.Value,TrackReply); } } for(String S:Fedex_TrackReply.keySet()){ if(!Old_Shipment_Facts.containsKey(S)){ Shipment_Facts__c ShippingInformation=new Shipment_Facts__c (); if(Fedex_TrackReply.get(S).TransactionDetail!=null) ShippingInformation.CustomerTransactionId__c=Fedex_TrackReply.get(S).TransactionDetail.CustomerTransactionId; ShippingInformation.OrderDestination__c=TrackingNumbers.get(S).id; New_Shipment_Facts.put(S,ShippingInformation); CompletedTrackDetails.put(S,Fedex_TrackReply.get(S).CompletedTrackDetails); }else{ CompletedTrackDetails.put(S,Fedex_TrackReply.get(S).CompletedTrackDetails); } } for(String S:CompletedTrackDetails.keySet()){ for(fedexComWsTrackV14.CompletedTrackDetail C:CompletedTrackDetails.get(S)){ if(New_Shipment_Facts.containsKey(S)){ if(C.DuplicateWaybill!=null) New_Shipment_Facts.get(S).DuplicateWaybill__c=C.DuplicateWaybill; TrackDetails.put(S,C.TrackDetails); } else{ if(C.DuplicateWaybill!=null) Old_Shipment_Facts.get(S).DuplicateWaybill__c=C.DuplicateWaybill; TrackDetails.put(S,C.TrackDetails); } } } for(String S:TrackDetails.keySet()){ for(fedexComWsTrackV14.TrackDetail T:TrackDetails.get(S)){ if(New_Shipment_Facts.containsKey(S)){ if(T.PackageCount!=null) New_Shipment_Facts.get(S).Total_Pieces__c=T.PackageCount; if(T.DeliveryAttempts!=null) New_Shipment_Facts.get(S).Delivery_Attempts__c=T.DeliveryAttempts; if(T.StatusDetail!=null) New_Shipment_Facts.get(S).Delivery_Status__c=T.StatusDetail.Description; if(T.DestinationAddress!=null){ New_Shipment_Facts.get(S).DestinationAddress__c='City :'+T.DestinationAddress.City+'\n'+'StateOrProvinceCode :'+T.DestinationAddress.StateOrProvinceCode +'\n'+'CountryCode :'+T.DestinationAddress.CountryCode+'\n'+'CountryName :'+T.DestinationAddress.CountryName; if(T.DestinationAddress.City!=null) New_Shipment_Facts.get(S).Destination_City__c=T.DestinationAddress.City ; if(T.DestinationAddress.CountryName!=null) New_Shipment_Facts.get(S).Destination_country__c=T.DestinationAddress.CountryName ; } if(T.PackageDimensions!=null){ New_Shipment_Facts.get(S).Dimensions__c=string.valueOf(T.PackageDimensions.Length)+'x'+string.valueOf(T.PackageDimensions.Width)+'x'+ string.valueOf(T.PackageDimensions.Height)+' in.'; } if(T.PackageWeight!=null) New_Shipment_Facts.get(S).PackageWeight__c=string.valueOf(T.PackageWeight.Value)+' '+T.PackageWeight.Units; if(T.Packaging!=null) New_Shipment_Facts.get(S).Packaging__c=T.Packaging; if(T.Service!=null) New_Shipment_Facts.get(S).Service__c=T.Service.Description; if(T.ShipperAddress!=null){ New_Shipment_Facts.get(S).ShipperAddress__c='City :'+T.ShipperAddress.City+'\n'+'StateOrProvinceCode :'+T.ShipperAddress.StateOrProvinceCode +'\n'+'CountryCode :'+T.ShipperAddress.CountryCode+'\n'+'CountryName :'+T.ShipperAddress.CountryName; if(T.ShipperAddress.City!=null) New_Shipment_Facts.get(S).Shipper_City__c=T.ShipperAddress.City; if(T.ShipperAddress.CountryName!=null) New_Shipment_Facts.get(S).Shipper_Country__c=T.ShipperAddress.CountryName; } if(T.TrackingNumber!=null) New_Shipment_Facts.get(S).TrackingNumber__c=T.TrackingNumber; if(T.ShipmentWeight!=null) New_Shipment_Facts.get(S).Total_shipment_weight__c=string.valueOf(T.ShipmentWeight.Value)+' '+T.ShipmentWeight.Units; if(T.Notification!=null) New_Shipment_Facts.get(S).Notification_Message__c=T.Notification.Message; if(T.Events!=null) TrackEvents.put(S,T.Events); Individual_Track_Detail.put(S,T); if(T.Payments!=null) New_Shipment_Facts.get(S).Terms__c=T.Payments[0].Description; } else { if(T.DestinationAddress!=null){ if(T.DestinationAddress.City!=null) Old_Shipment_Facts.get(S).Destination_City__c=T.DestinationAddress.City ; if(T.DestinationAddress.CountryName!=null) Old_Shipment_Facts.get(S).Destination_country__c=T.DestinationAddress.CountryName ; } if(T.Packaging!=null) Old_Shipment_Facts.get(S).Packaging__c=T.Packaging; if(T.Payments!=null) Old_Shipment_Facts.get(S).Terms__c=T.Payments[0].Description; if(T.Notification!=null) Old_Shipment_Facts.get(S).Notification_Message__c=T.Notification.Message; if(T.PackageDimensions!=null){ Old_Shipment_Facts.get(S).Dimensions__c=string.valueOf(T.PackageDimensions.Length)+'x'+string.valueOf(T.PackageDimensions.Width)+'x'+ string.valueOf(T.PackageDimensions.Height)+' in.'; } if(T.ShipmentWeight!=null) Old_Shipment_Facts.get(S).Total_shipment_weight__c=string.valueOf(T.ShipmentWeight.Value)+' '+T.ShipmentWeight.Units; if(T.PackageCount!=null) Old_Shipment_Facts.get(S).Total_Pieces__c=T.PackageCount; if(T.ShipperAddress!=null){ if(T.ShipperAddress.City!=null) Old_Shipment_Facts.get(S).Shipper_City__c=T.ShipperAddress.City; if(T.ShipperAddress.CountryName!=null) Old_Shipment_Facts.get(S).Shipper_Country__c=T.ShipperAddress.CountryName; } if(T.PackageWeight!=null) Old_Shipment_Facts.get(S).PackageWeight__c=string.valueOf(T.PackageWeight.Value)+' '+T.PackageWeight.Units; if(T.Service!=null) Old_Shipment_Facts.get(S).Service__c=T.Service.Description; if(T.Events!=null) TrackEvents.put(S,T.Events); Individual_Track_Detail.put(S,T); } } } for(String S:TrackEvents.keySet()){ eventTimeStamp=DateTime.newInstance(2017,1,1,1,1,1); for(fedexComWsTrackV14.TrackEvent T:TrackEvents.get(S)){ if(New_Shipment_Facts.containsKey(S)){ if(eventTimeStamp Total_Shipment_Facts=new Map(); for(Shipment_Facts__c S:Shipment_Facts){ Total_Shipment_Facts.put(S.TrackingNumber__c,S); } if(!TrackEvents.isEmpty()) for(String S:TrackEvents.keySet()){ for(fedexComWsTrackV14.TrackEvent T:TrackEvents.get(S)){ if(Existing_Travel_History_TimeStamps.get(S)!=null) { if(!Existing_Travel_History_TimeStamps.get(S).contains(T.Timestamp.format())){ Travel_History__c History=new Travel_History__c(); if(T.Timestamp!=null){ History.EventTimestamp__c=T.Timestamp; History.EventTime__c=T.Timestamp.format('h:mm a'); History.Day_Of_Event__c=T.Timestamp.format('EEEE'); History.Date_Of_Event__c=T.Timestamp.date(); } if(T.EventType!=null) History.EventType__c=T.EventType; if(T.EventDescription!=null) History.EventDescription__c=T.EventDescription; if(T.StatusExceptionCode!=null) History.EventStatusExceptionCode__c=T.StatusExceptionCode; if(T.ArrivalLocation!=null) History.EventArrivalLocation__c=T.ArrivalLocation; if(T.StatusExceptionDescription!=null) History.EventStatusExceptionDescription__c=T.StatusExceptionDescription; if(T.StationId!=null) History.EventStationId__c=T.StationId; if(T.Address!=null){ History.EventAddress__c='City : '+T.Address.city+'\n'+'StateOrProvinceCode : '+T.Address.StateOrProvinceCode+'\n' +'CountryCode : '+T.Address.CountryCode+'\n'+'CountryName : '+T.Address.CountryName+ '\n'+'Residential : '+T.Address.Residential; History.Event_City__c=T.Address.city; } History.TrackingNumber__c=S; History.Shipment_Facts__c=Total_Shipment_Facts.get(S).id; Travel_History.add(History); NewTravel_History.put(S,new List {History}); } } else{ Travel_History__c History=new Travel_History__c(); if(T.Timestamp!=null){ History.EventTimestamp__c=T.Timestamp; History.EventTime__c=T.Timestamp.format('h:mm a'); History.Day_Of_Event__c=T.Timestamp.format('EEEE'); History.Date_Of_Event__c=T.Timestamp.date(); } if(T.EventType!=null) History.EventType__c=T.EventType; if(T.EventDescription!=null) History.EventDescription__c=T.EventDescription; if(T.StatusExceptionCode!=null) History.EventStatusExceptionCode__c=T.StatusExceptionCode; if(T.ArrivalLocation!=null) History.EventArrivalLocation__c=T.ArrivalLocation; if(T.StatusExceptionDescription!=null) History.EventStatusExceptionDescription__c=T.StatusExceptionDescription; if(T.StationId!=null) History.EventStationId__c=T.StationId; if(T.Address!=null){ History.EventAddress__c='City : '+T.Address.city+'\n'+'StateOrProvinceCode : '+T.Address.StateOrProvinceCode+'\n' +'CountryCode : '+T.Address.CountryCode+'\n'+'CountryName : '+T.Address.CountryName+ '\n'+'Residential : '+T.Address.Residential; History.Event_City__c=T.Address.city; } History.TrackingNumber__c=S; History.Shipment_Facts__c=Total_Shipment_Facts.get(S).id; Travel_History.add(History); NewTravel_History.put(S,new List {History}); } } } for(fedexComWsTrackV14.TrackDetail T:Individual_Track_Detail.values()){ if(TrackEvents.containsKey(T.TrackingNumber)) for(Travel_History__c History:Travel_History){ if(T.TrackingNumber==History.TrackingNumber__c){ if(T.OperatingCompany!=null) History.OperatingCompany__c=T.OperatingCompany; if(T.OperatingCompanyOrCarrierDescription!=null) History.OperatingCompanyOrCarrierDescription__c=T.OperatingCompanyOrCarrierDescription; if(T.OriginStationId!=null) History.OriginStationId__c=T.OriginStationId; if(T.PackageCount!=null) History.PackageCount__c=T.PackageCount; if(T.PackageSequenceNumber!=null) History.PackageSequenceNumber__c=T.PackageSequenceNumber; if(T.Packaging!=null) History.Packaging__c=T.Packaging; if(T.PackagingType!=null) History.PackagingType__c=T.PackagingType; if(T.PhysicalPackagingType!=null) History.PhysicalPackagingType__c=T.PhysicalPackagingType; if(T.PossessionStatus!=null) History.PossessionStatus__c=T.PossessionStatus; if(T.Service!=null) History.Service__c='ServiceType : '+T.Service.Type_x+'\n'+'ServiceDescription : '+T.Service.Description+'\n'+'ServiceShortDescription : '+T.Service.ShortDescription; if(T.ServiceCommitMessage!=null) History.ServiceCommitMessage__c=T.ServiceCommitMessage; if(T.StatusDetail!=null){ History.StatusCode__c=T.StatusDetail.Code; History.StatusCreationTime__c=T.StatusDetail.CreationTime; History.StatusDescription__c=T.StatusDetail.Description; if(T.StatusDetail.Location!=null){ History.StatusLocation__c='City : '+T.StatusDetail.Location.City+'\n'+'StateOrProvinceCode : '+T.StatusDetail.Location.StateOrProvinceCode+'\n' +'CountryCode : '+T.StatusDetail.Location.CountryCode+'\n'+'CountryName : '+T.StatusDetail.Location.CountryName+ '\n'+'Residential : '+T.StatusDetail.Location.Residential; } } if(T.TrackingNumberUniqueIdentifier!=null) History.TrackingNumberUniqueIdentifier__c=T.TrackingNumberUniqueIdentifier; } } } if(!Travel_History.isEmpty()) Insert Travel_History; } /*finish method */ global void finish(Database.BatchableContext bc){ } } this is the batch apex i have done,please provide appropriate result.
pradeep kumar s 1pradeep kumar s 1
sorry for this this is not good at me.i have sent this from my mail.so it happened and it allows 32000 characters only,so i can not do.
PawanKumarPawanKumar
Hi Pradeep,
No Problem. I have seen some insert in your code. Inside for loop, you are doing web service callout if something contains in Existing_Shipment_Facts and if something does not found then you are inserting the record then calling webservice. So what i would suggest You should store the object in List then in last you should do bulk insert. Then you will not get any error.

for (String S: TrackingNumbers.keySet()) {
      if (Existing_Shipment_Facts.containsKey(S)) {
       if (Existing_Shipment_Facts.get(S).Delivery_Status__c != 'Delivered') {
        PackageIdentifier.Value = Existing_Shipment_Facts.get(S).TrackingNumber__c;
        fedexComWsTrackV14.TrackReply TrackReply = new fedexComWsTrackV14.TrackReply();
        TrackReply = TrackServicePort.track(WebAuthenticationDetail, Details, TransactionDetail, Version, SelectionDetails, 10, ProcessingOptions);
        if (TrackReply != null) Fedex_TrackReply.put(PackageIdentifier.Value, TrackReply);
        if (TrackReply.CompletedTrackDetails != null) CompletedTrackDetails.put(PackageIdentifier.Value, TrackReply.CompletedTrackDetails);
        Old_Shipment_Facts.put(PackageIdentifier.Value, Existing_Shipment_Facts.get(S));
       }
      } else {
             //insert new Shipment_Facts__c(
// add list.(Shipment_Facts__c);
}
}

Regards,
Pawan Kumar
 
pradeep kumar s 1pradeep kumar s 1
@isTest
global class WebServiceMockCallOut_Test implements WebServiceMock{
   global void doInvoke(
           Object stub,
           Object request,
           Map<String, Object> response,
           String endpoint,
           String soapAction,
           String requestName,
           String responseNS,
           String responseName,
           String responseType) {
           
           fedexComWsTrackV14.TrackReply response_x=new fedexComWsTrackV14.TrackReply ();
           response_x.HighestSeverity='success';
           response_x.Notifications=new List<fedexComWsTrackV14.Notification> ();
           response_x.TransactionDetail=new fedexComWsTrackV14.TransactionDetail();
           response_x.Version=new fedexComWsTrackV14.VersionId();
           response_x.CompletedTrackDetails=new List<fedexComWsTrackV14.CompletedTrackDetail> ();
           response.put('response_x',response_x);
   }
}

hi pawan this is my web service mok callout class.
@isTest
private class TrackingStatus_BatchApex_Test {
    @testSetup static void setup() {
       Account acct = new Account(Name='test');
    	insert acct ;
        Contact contact = new contact(LastName = 'portalContact', AccountId = acct.Id);
   		 insert contact;
    	Profile profile = [SELECT Id FROM Profile WHERE Name='Customer Community User']; 
        User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = profile.Id, 
            ContactId = contact.Id,
            TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
        insert u;
        
        ProgramWindow__c pw=new ProgramWindow__c(Account__c=acct.Id,active__c=true,ProgramWindow_Name__c='Bogle Order Window');
        insert pw;
        
        program__c p=new program__c(Account__c=acct.Id,Active__c=true,
                                    Closing_Date__c=system.today()+35,In_Market_Date__c=system.today()+10,
                                    Program_Name__c='Bogle FY18 Summer',Program_Type__c='Pre-Buy',
                                    ProgramWindow__c=pw.Id,Start_Date__c=system.today()+1);
        insert p;
        
        Order__c ord = new Order__c();
        ord.Account__C = acct.id;
        ord.OrderFor__c=u.id;
        ord.Order_Status__c = 'Open';
        ord.Order_Date__c = System.today();
        ord.program__c = p.id;
        insert ord;
        
        Country__c c = new Country__c(Country_Code__c='US', Country_Name__c ='US');
        insert c;
        
        State__c state = new State__c( Country__c= c.id, State_Code__c='NY',  State_Name__c='Newyork');
        insert state;
        
         Shipping_Method__c shipmethod = new Shipping_Method__c(Shipping_Method_Name__c='testshipmethod', Active__c = true, Account__c = acct.id);
        insert shipmethod ;
         Shipping_Method__c shipmethod1 = new Shipping_Method__c(Shipping_Method_Name__c='testshipmethod', Active__c = true, Account__c = acct.id, ApprovalRequired__c = true);
        insert shipmethod1 ;
        
        
        AddressBook__c address = new AddressBook__c(Address__c='addr1', State__c= state.id, Destination_Name__c = 'Dest1', Shipto_Company__c = 'shiptocomp' , Country__c = c.id, Active__c = true, Account__c = acct.id);
        insert address;
        
        OrderDestination__c od = new OrderDestination__c();
        od.AddressBook__c = address.id;
        od.Order__c = ord.id;
        od.Shipping_Method__c = shipmethod.id;
        od.TrackingNos__c='123456';
        insert od;
        OrderDestination__c od1 = new OrderDestination__c();
        od1.AddressBook__c = address.id;
        od1.Order__c = ord.id;
        od1.Shipping_Method__c = shipmethod.id;
        od1.TrackingNos__c='';
        insert od1;
        
             Shipment_Facts__c Shipment_Facts=new Shipment_Facts__c(COD__c='12345',CustomerTransactionId__c='12345',Deliveried_to__c='test',Delivery_Attempts__c=3,
                                         Delivery_Status__c='picked up',DestinationAddress__c='Testing',Destination_City__c='Test',Destination_country__c='USA',
                                          Dimensions__c='12x15x16 in',DuplicateWaybill__c=false,Notification_Message__c='',OrderDestination__c=od.Id,PackageWeight__c='1.5 lb',
                                          Packaging__c='packing',Service__c='FEDEX',ShipperAddress__c='Test',Shipper_City__c='Test',Shipper_Country__c='India',Special_Handling_Section__c='Test',
                                          Standard_transit__c=DateTime.newInstanceGmt(2017, 5, 25, 2, 15, 06),Terms__c='shipper',Total_Pieces__c=3,Total_shipment_weight__c='3.5 lb',TrackingNumber__c='123456');
        
        insert Shipment_Facts;
        
        Travel_History__c Travel_History=new Travel_History__c(EventTime__c='2:15 PM',Event_City__c='Test',Date_Of_Event__c=Date.newInstance(2017, 7, 25),
                                                              Day_Of_Event__c='Tuesday',EventDescription__c='Delivered',EventArrivalLocation__c='USA',EventAddress__c='USA',Shipment_Facts__c=Shipment_Facts.Id);
        
        insert Travel_History;
        FedEx_Production_Integration__c customSetting=new FedEx_Production_Integration__c();
        customSetting.Name='Bogle User1';
        customSetting.Account_Number__c='45688';
        customSetting.Developer_Key__c='AbC';
        customSetting.Developer_Password__c='12A';
        customSetting.Meter_Number__c='123445';
        insert customSetting;
         
        
    }
@isTest
    static  void constructorTest(){
        
        Shipment_Facts__c s=[SELECT Id,COD__c,CustomerTransactionId__c,Deliveried_to__c,Delivery_Attempts__c,Delivery_Status__c,DestinationAddress__c,
                             Destination_City__c,Destination_country__c,Dimensions__c,DuplicateWaybill__c,Notification_Message__c,OrderDestination__c,
                             PackageWeight__c,Packaging__c,Service__c,ShipperAddress__c,Shipper_City__c,Shipper_Country__c,Special_Handling_Section__c,
                             Standard_transit__c,Terms__c,Total_Pieces__c,Total_shipment_weight__c,TrackingNumber__c FROM Shipment_Facts__c LIMIT 1];
        
		List<OrderDestination__c> od=[SELECT Id,TrackingNos__c FROM OrderDestination__c];       

        FedEx_Production_Integration__c f=[SELECT Name,Account_Number__c,Developer_Key__c,Developer_Password__c,Meter_Number__c FROM FedEx_Production_Integration__c WHERE Name='Bogle User1' ];
        
        
        Database.executeBatch(new TrackingStatus_BatchApex(),10);
        
        Test.startTest();
        Test.setMock(WebServiceMock.class, new WebServiceMockCallOut_Test());
        //FedexWebservice2 f1=new FedexWebservice2();
        //f1.sendRequest();
        
        Test.stopTest();
    }
}

this is the test class for that batch apex.so please let me know,what should i do now?
PawanKumarPawanKumar
Hi Pradeep,
can you try below code from line#96 to 103. I have just changed the sequence as you are caling your batch first then you are setting Mock.

        Test.setMock(WebServiceMock.class, new WebServiceMockCallOut_Test());
        Test.startTest();
        Database.executeBatch(new TrackingStatus_BatchApex(),10);
        //FedexWebservice2 f1=new FedexWebservice2();
        //f1.sendRequest();
        
        Test.stopTest();

Regards,
Pawan Kumar
pradeep kumar s 1pradeep kumar s 1
Thanks Pawan kumar,
but it is working with this class--""//FedexWebservice2 f1=new FedexWebservice2();
        //f1.sendRequest();  ""successfully.-it takes 100 % code coverage but in this code no insert or update operation is doing.
can i know what the reason is?
pradeep kumar s 1pradeep kumar s 1
still it is not working what you have modified,still i am getting the same error
pradeep kumar s 1pradeep kumar s 1
Pawan,it is working in synchronous classes(without batch apex) and the class is not working in batch apex.
PawanKumarPawanKumar
Hi Pradeep,
The class is working synchrously because when you call your class it does not have DML operation(Insert/Update/delete/upsert). You are calling your web service independently. But when you call your batch class this is failing because before calling your web service class there is a insert/update in your execute method/ in dependent class. To identify just run below line in your developer class as anonymous block and see the debug log for the below bold items in the last.

// run below line as anonymous block from develoer console.
Database.executeBatch(new TrackingStatus_BatchApex(), 10);

Note : If Number of DML statements is not 0 out 150, it means in your batch somewhere dml has been performed before calling your web service.


Number of SOQL queries: 2 out of 100
Number of query rows: 2 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 1 out of 150
Number of DML rows: 1 out of 10000
Maximum CPU time: 0 out of 10000
Maximum heap size: 0 out of 6000000
Number of callouts: 0 out of 100
Number of Email Invocations: 0 out of 10
Number of future calls: 0 out of 50
Number of queueable jobs added to the queue: 0 out of 50
Number of Mobile Apex push calls: 0 out of 10

Please let me know the output.

 
Bernice BotesBernice Botes

Good Day Pradeep and Pawan, 

I'm a novice salesforce developer and wasn't sure if this was even possible. This makes me very hopeful. I was wondering if you could just perhaps advice me on whether or not I am understanding the flow of processes. 

I have an apex class in which I do my SOAP Api callout. Then I have a class in which I do a batch processing. And a schedule class in which I schedule the actual callout. 

The scheduler calls the batch who in return calls the batch who then calls the web service class. 

See code below.
Thank you in advance for the advice

 

//SOAP apex class

global with sharing class FmeSOAPCallout{
    global static ElephantService.Service1Soap service = new ElephantService.Service1Soap();
    
    webservice static String getObject(String CompanyID, String lmTime, String tz){
        String webResult = service.SkyQMobileUnits(CompanyID, lmTime, tz);
        return webResult;
    }
    
}
 
//batch callout
public with sharing class BatchCallout implements Database.Batchable<SObject>, Database.AllowsCallouts{
 public Database.QueryLocator start(Database.BatchableContext BC){
 String results = FmeSOAPCallout.getObject('1091','0','120');
//Deserialize the object and saves it in the correct related fields
FmeProcessCallout.processData(results);
}
public void execute(Database.BatchableContext info, List<SObject> opportunities){}
public void finish(Database.BatchableContext info){}
}
 
global class Scheduler_Class implements Schedulable{
      public static String sched = '0 30 00 * *?'; //every 30 minutes
    global static String scheduleCallout(){
             Scheduler_class SC = new Scheduler_class();
            return System.schedule('My batch Job', sched, SC):
  }
  global void execute(SchedulableContext sc){
      BatchCallout bc = new BatchCallout();
     ID batchprocessId = Database.execute(bc, 50);
     }
}