6
@HttpPost
global static Map <String,String> doPost(String firstName, String lastName, 
    String phone, String email) {
    Lead lead = new Lead();

    Map <String,String> sta = new Map <String,String>();
    lead.FirstName = firstName;
    lead.LastName = lastName;
    lead.phone = phone;
    lead.Email = email;
    lead.Company = 'agf';
    lead.Status = 'Open - Not Contacted';

    Database.SaveResult db = Database.insert(lead, false);
    if(db.isSuccess())
    {
        sta.put('isSuccess','True');
        sta.put('leadId',lead.Id);
        sta.put('status','Success');
    }
    else
    {

        sta.put('isSuccess','False');
        sta.put('leadId','');
        sta.put('status','failure');
        sta.put('message','Requested Resources Does not found');
        sta.put('errorCode','Not Found');
        db.getErrors();

    }

    return sta;
}

how to write test code for above rest api service

3

1 Answer 1

6
//As Per Best Practice it is important to instantiate the Rest Context

 RestRequest req = new RestRequest();
  RestResponse res = new RestResponse();

req.requestURI = '/services/apexrest/Lead';  //Request URL
req.httpMethod = 'POST';//HTTP Request Type
RestContext.request = req;
RestContext.response= res;

MyRestResource s=new MyRestResource ();
 Map <String,String> stas=s.dopost('Test,'Test','1232','[email protected]');

system.assert(stas.get('isSuccess')==true);//Similarly assert rest as well

For the REST API Wrapper classes i had blogged this as below to help

http://cloudyworlds.blogspot.in/2012/12/writing-test-classes-for-apex-rest.html

Hope that helps

3
  • Its not clear to me why the need to instantiate the RestContext in this case, because the method doPost does not even refer to the RestContext or the request? Dec 26, 2016 at 21:23
  • 1
    @BradThomas - In practice for this OP's specific use case, it is not needed.
    – Eric
    Dec 26, 2016 at 22:04
  • @mohith I followed your blog post on this issue and my question, what if I am not using any wrapper? Do I need to use a wrapper class? Jun 10, 2017 at 5:24

You must log in to answer this question.

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