You need to sign in to do that
Don't have an account?
Baylor Peak
Help with Test Class for Batch Apex with HTTP callouts
Hello all,
I wrote a batch class that sends data to an endpoint but I am not good with test classes at all:(
Here is my code:
global class CircleMembershipBatchProcesor implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful { // Start Method global Integer recordsProcessed = 0; global Database.QueryLocator start(Database.BatchableContext bc) { String apexClassId = '01p1U00000QoPw6QAF'; List<AsyncApexJob> jobs = [SELECT CreatedDate FROM AsyncApexJob WHERE JobType = 'BatchApex' AND ApexClassId =: apexClassId ORDER BY CreatedDate DESC LIMIT 1]; DateTime jobDate = null; if (jobs != null && jobs.size() > 0) { System.debug('using AsyncApexJob'); AsyncApexJob job = jobs[0]; jobDate = job.CreatedDate; } else { System.debug('using System.now()'); jobDate = System.now().addHours(-1); } String dateStr = jobDate.format('yyyy-MM-dd\'T\'HH:mm:ss.SSSZ'); System.debug(dateStr); String Query='SELECT Id, FirstName, LastName, Email, npo02__MembershipJoinDate__c, npo02__MembershipEndDate__c, npo02__LastMembershipDate__c FROM Contact WHERE npo02__MembershipJoinDate__c != NULL AND (CreatedDate > ' + dateStr + ' OR LastModifiedDate > ' + dateStr + ')'; return Database.getQueryLocator(Query); } // Execute Method global void execute(Database.BatchableContext bc, List<Contact> scope){ String JSONString = JSON.serialize(scope); HttpRequest request = new HttpRequest(); HttpResponse response = new HttpResponse(); Http http = new Http(); // Retrieve username and password from Custom Setting CircleMembershipBatchSettings__c myCS1 = CircleMembershipBatchSettings__c.getValues('default'); String username = myCS1.username__c; String password = myCS1.password__c; // Add basic authentication to header // Create blob of user:pass Blob headerValue = Blob.valueOf(username + ':' + password); // Base 64 Encode the blob and prepend "Basic " String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue); // Add the basic auth string to the Request Header request.setHeader('Authorization', authorizationHeader); request.setHeader('Content-Type', 'application/json'); request.setEndpoint('https://th-webhook-test.herokuapp.com/webhook'); request.setMethod('POST'); request.setBody(JSONString); response = http.send(request); if (response.getStatusCode() == 200) { String jsonResponse = response.getBody(); System.debug('Response-' + jsonResponse); System.debug(JSONString); } else { throw new CircleMembershipBatchProcesorException('Callout was not successful'); } } // Finish Method global void finish(Database.BatchableContext bc){ Id job= bc.getJobId(); System.debug(job); } }
Greetings!
Can you please check the sample code provided in the below document to cover Httprequest:
https://salesforce.stackexchange.com/questions/185163/a-testclass-for-restresource-httppost
Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.
Warm Regards,
Shirisha Pathuri
For this part
Would I instead use? Also, how do I also test the Batch Apex wihin the same Test class?https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm
For testing you batch put the Database.executeBatch between Test.startTest() and Test.stopTest()
If this solves your issue please mark this answer as correct. It may help others.
OK, here is what I have so far fro my Test Class, but only getting 36% code coverage:
May I get some assistance in finishing this class, what am I missing, etc? I'm getting there, but not yet;)Regards,
Baylor
If you are getting inside the execute method please show me which lines are covered and which one are not.
I ll wait for your reply
Here is what is showing that is not covered:
Under Start Method:
Under Execute Method:
Under Finsh Method:
Oops, here are the line that are covered taht you asked for:
Start:
Execute:
Finish:
And thank you for helping me with this:)