9

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?

1 Answer 1

20

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();

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .