I am doing do a callout trough a processbuilder with a future call. Before I do the call I get some variables from a custom setting. When I do an insert in my testclass for my custom setting I get the error System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out. How do I advoid this?
See my class:
public class or_service {
@InvocableMethod
public static void InvocePutProperty(List<String> pNames) {
for (String pName : pNames) {
PutProperty(pName);
}
}
public static void PutProperty(String pName) {
List<Orbirental_Service__c> os = null;
Http http = new Http();
HttpRequest request = new HttpRequest();
try {
os = [SELECT Url__c, ApiKey__c FROM Orbirental_Service__c LIMIT 1];
}catch(QueryException ex) {
os = null;
}
request.setEndpoint(os[0].Url__c +'v1/properties');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
request.setHeader('X-ORBIRENTAL-APIKEY', os[0].ApiKey__c);
// Set the body as a JSON object
request.setBody('{"type": "HOUSE",'+
'"name":'+ pName +
',"agencyUid": "0000000-000-000-00-000",'+
'"baseGuests": 4,'+
'"maximumGuests": 6,'+
'"baseDailyRate": 220,'+
'"city": "Utrecht",'+
'"state": "Utrecht",'+
'"acceptInstantBook": false,'+
'"isActive": true}');
HttpResponse response = http.send(request);
// Parse the JSON response
if (response.getStatusCode() != 200) {
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
} else {
System.debug(response.getBody());
}
//return response;
}
}
Test
@isTest
private class or_serviceTest {
@isTest static void testGetAgencies() {
Orbirental_Service__c setting = new Orbirental_Service__c(ApiKey__c = 'abcdefgh',Url__c = 'http://api.sandbox.orbirental.com/');
insert setting;
// Create the mock response based on a static resource
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('GetAgenciesResource');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
Test.setMock(HttpCalloutMock.class, mock);
HttpResponse result = or_service.GetAgencies();
System.assertNotEquals(null,result,
'The callout returned a null response.');
System.assertEquals(200,result.getStatusCode(),
'The status code is not 200.');
System.assertEquals('application/json;charset=UTF-8',
result.getHeader('Content-Type'),
'The content type value is not expected.');
List<Object> results = (List<Object>)
JSON.deserializeUntyped(result.getBody());
List<Object> agency = (List<Object>) results.get('agency');
System.assertEquals(1, agency.size(),
'The array should only contain 1 item.');
}
}