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

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','dummymail@test.com');

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

|improve this answer|||||
  • 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? – Brad Thomas Dec 26 '16 at 21:23
  • 1
    @BradThomas - In practice for this OP's specific use case, it is not needed. – Eric Dec 26 '16 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? – codeinprogress Jun 10 '17 at 5:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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