1
votes

I've created a basic frontend that dips into my force.com data by way of a Public Guest User and a webservice call. Essentially, the code is requesting the Rate (aka cost) of various items that a user may select (line 10). Everything is working on the sandbox as expected. However, I'm stuck writing a test class due to the web service calls, which I've, surprisingly, never worked with in conjunction with force.com before.

My specific hangup is how to populate the details in the test class that would normally be coming in as part of a URL string (lines 7 & 8)? Outside that specific, and, I assume, fairly routine, issue I know how to structure the test class for this. Any input would be much appreciated.

I'm attempting to make an APEX Test Class for the following code:

@RestResource(urlMapping='/rowsrate')
global class ROWSRate {
    @HttpGet
    global static void doGet(){ // grabs the Rate (cost) information for the provided Resource Type, ie Police Officer and returns a JSON object
        String callback = RestContext.request.params.get('callback');

        Date endDateParam = Date.parse(RestContext.request.params.get('enddate')); // transmute string parameter to date on the fly
        String resourceName = RestContext.request.params.get('resctype');

        List<ROWS_RateRange__c> resourceTypeList = [select Cost__c, Rate__r.Name from ROWS_RateRange__c where LookupName__c = :resourceName and Start_Date__c <= :endDateParam and End_Date__c >= :endDateParam];

        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/javascript');
        res.responseBody = Blob.valueOf(callback + '(' + JSON.serialize(resourceTypeList) + ')');
    }
}

PS I've done my fair share of Googling on the topic, but found mostly ancient items. Perhaps my Google skills are off today.

2

2 Answers

0
votes
0
votes

Here's the class I ended up building to test the above. Full coverage.

@isTest
private class ROWSRateTest {      
    static testMethod void testGoodRate(){
    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/rowsrate';  

    //creating test Rate & RateRange
    ROWS_Rate__c testRate = ROWSDataFactoryTest.createROWSRatewithRange();
    ROWS_RateRange__c testRateRange = [Select id, Cost__c from ROWS_RateRange__c where Rate__c =: testRate.Id];

    req.addParameter('callback', 'test');
    // fake the passed parameters
    req.addParameter('enddate', '06/30/2015');
    req.addParameter('resctype', 'isTest Rate');
    req.httpMethod = 'GET';
    RestContext.request = req;
    RestContext.response = res;

    Test.startTest();
    ROWSRate.doGet();
    Test.stopTest();
    String testBlob = res.responseBody.toString();

    System.assert(testBlob.contains(testRate.Name));
    system.assert(testBlob.contains(testRateRange.Cost__c.format()));
}
// I'm not sure what else we could test since it's a pretty basic class
}