Skip to content

Instantly share code, notes, and snippets.

@joshbirk
Last active August 29, 2015 13:58
Show Gist options
  • Select an option

  • Save joshbirk/10024859 to your computer and use it in GitHub Desktop.

Select an option

Save joshbirk/10024859 to your computer and use it in GitHub Desktop.
HTTP Mock Extra Credit
/*
This is an Apex class which calls out to an endpoint to find new merchandise items to be inserted into the system.
Before it can be deployed to production, however, it needs a unit test. Since it makes an HTTP callout, however,
the unit test will require a mock class.
Before you can test the class, you will also need to open a Remote Site to let your Salesforce instance know
it is a legitimate site:
1. Go to Setup | System Administration | Security Controls | Remote Site Settings.
2. Click New.
3. For Remote Site Name, enter warehousedatapush
4. For Remote Site URL, enter http://warehousedatapush.herokuapp.com
To complete this extra credit:
1. Create a unit test which achieves 75% against this class, using the mock class below
For extra extra credit:
Utilize the following, or similarly formatted CSV as test data via a static resource:
https://gist.githubusercontent.com/joshbirk/5079255/raw/301cbbeb6a25b937aa315f1faef93b160046732a/3_WarehousePull.cls
*/
public with sharing class WarehousePullData {
public WarehousePullData() {}
//WarehousePullData.pullData();
public static String pullData() {
// Instantiate a new http object
Http h = new Http();
// Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
HttpRequest req = new HttpRequest();
req.setEndpoint('http://warehousedatapush.herokuapp.com/');
req.setMethod('GET');
// Send the request, and return a response
HttpResponse res = h.send(req);
Map<String, Object> data = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
List<Object> items = (List<Object>)data.get('Items');
List<Merchandise__c> new_items = new List<Merchandise__c>();
for(Object item : items) {
Map<String, Object> item_data = (Map<String, Object>)item;
Merchandise__c merch = new Merchandise__c();
merch.Name = (String)item_data.get('Name');
merch.Quantity__c = (Decimal)item_data.get('Quantity');
merch.Price__c = (Decimal)item_data.get('Price');
new_items.add(merch);
}
insert new_items;
return 'Done';
}
}
@isTest
global class WarehouseMock implements HttpCalloutMock {
// Implement this interface method
global HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{ "Items": [ { "Name": "Laptop From Endpoint", "Price": 2999.99, "Quantity": 4 }, { "Name": "Super Duper Laptop", "Price": 3999.99, "Quantity": 4 } ] }');
res.setStatusCode(200);
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment