I´m having problems with url parameters (req.requestURI) in my test class.

This is my code.

REST CLASS:

@RestResource(urlMapping='/Accounts/*')
global class StoreController {



   @HttpGet
    global static String getAccounts() {


        integer pageNumber=integer.valueof(RestContext.request.params.get('page'));
        string  ptime=RestContext.request.params.get('time');
        string  hash=RestContext.request.params.get('hash');

    }

REST TEST CLASS:

@isTest
private class StoreControllerTest {

    static testMethod void testGet() {


    //do request
    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    req.requestURI = 'https://dev-my-my.cs14.force.com/mine/services/apexrest/Accounts?page=0&time=1390296387&hash=1wer2547';  


    req.httpMethod = 'GET';
    RestContext.request = req;
    RestContext.response = res;

        String results = StoreController.getAccounts();

    }
}

When i run test class i get the error:

System.NullPointerException: Argument 1 cannot be null 

for line :

integer pageNumber=integer.valueof(RestContext.request.params.get('page'));

Looks like parameters are not taken from url 'https://dev-my-my.cs14.force.com/mine/services/apexrest/Accounts?page=0&time=1390296387&hash=1wer2547'

when i run the test class.Please can you help me with this?

up vote 15 down vote accepted

Change your test class to use the RestRequest.addParameter method. This method is used for setting parameters to be used by the webservice in a test.

You should also use a relative URL for the request URI value instead of hardcoding a fully qualified URL. I would also suggest adding some assertions to the test method.

@isTest
private class StoreControllerTest {

    static testMethod void testGet() {

        //do request
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();

        req.requestURI = '/services/apexrest/Accounts';  
        req.addParameter('page', '0');
        req.addParameter('time', '1390296387');
        req.addParameter('hash', '1wer2547');

        req.httpMethod = 'GET';
        RestContext.request = req;
        RestContext.response = res;

        String results = StoreController.getAccounts();

    }
}
  • This is a great answer, that's hard to find elsewhere on Google, esp. example on using relative url and use of addParameter. +1 – Brad Thomas Apr 8 '14 at 16:31
  • I've been spending 2 hard working days just to get this answer..you rock Mark..thanks a lot! – Jayson Faderanga Feb 7 '17 at 2:36

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.