You need to sign in to do that
Don't have an account?
Charisse de Belen
How do I test running batchable Apex from a REST endpoint?
Hello everyone,
I'm trying to create a REST endpoint that will execute a batch job. What I have now looks like this:
Is this on the right track? How do I unit test this? Here's the beginnings of a potential unit test:
Please let me know if I'm heading in the right direction.
I'm trying to create a REST endpoint that will execute a batch job. What I have now looks like this:
@RestResource(urlMapping='/runBatch') global class BatchRestWebService { @HttpPost global static void runBatch() { BatchJob restBatchJob = new BatchJob(); Database.executeBatch(restBatchJob, 50); } }
Is this on the right track? How do I unit test this? Here's the beginnings of a potential unit test:
@isTest private class TestBatchRestWebService { @isTest static void test() { RestRequest request = new RestRequest(); request.requestURI = 'https://my-dev-org.salesforce.com/services/apexrest/runBatch'; request.httpMethod = 'POST'; RestContext.request = request; // Now what? } }
Please let me know if I'm heading in the right direction.
I found this Stack Exchange thread (http://salesforce.stackexchange.com/questions/4988/writing-test-classes-for-apex-restservice) and ended up doing the following:
REST endpoint
Test class
The RestContext stuff makes more sense now, and the test results are successful. Thanks for your input!
All Answers
Please use this code.
@isTest
global class TestBatchRestWebService implements HttpCalloutMock {
@isTest
global static void test() {
Test.startTest() ;
BatchRestWebService.runBatch();
Test.startTest() ;
}
global HTTPResponse respond(HTTPRequest req) {
//RestRequest request = new RestRequest();
//request.requestURI = 'https://my-dev-org.salesforce.com/services/apexrest/runBatch';
//request.httpMethod = 'POST';
/// RestContext.request = request;
// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('');
req.setEndpoint('');
req.setMethod('');
res.setStatusCode(200);
return res;
}
}
Please pass the endpoint and body and method name to above example code
Can you explain what your code is doing? It seems like this is testing a callout to an external REST API, but I'm looking for a way to mock a request from an external system (ie. .NET) to my endpoint. Am I overthinking this?
I found this Stack Exchange thread (http://salesforce.stackexchange.com/questions/4988/writing-test-classes-for-apex-restservice) and ended up doing the following:
REST endpoint
Test class
The RestContext stuff makes more sense now, and the test results are successful. Thanks for your input!