You need to sign in to do that
Don't have an account?
mandyc
Help writing unit test for REST class
I have a REST class that creates new lead records. See below:
@RestResource(urlMapping='/v.1/leads/*') global with sharing class LeadRestSvc { @HttpPost global static String doPost(String firstname, String lastname) { RestRequest req = RestContext.request; //see if a name was part of the URI String leadName = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1); if (leadName == '') { Savepoint sp = Database.setSavePoint(); try { //populate a new Lead object Lead l = new Lead(); l.FirstName = firstname; l.LastName = lastname; insert l; return 'success'; } catch (DMLException e1) { Database.rollback(sp); return e1.getDMLMessage(0); } catch (Exception e2) { Database.rollback(sp); return e2.getMessage(); } } else { return 'Invalid operation'; } }
Now I need to write a unit test and am having difficulty. I've tried following the few GET examples online but without success.
I tried the following but I get this error : "Compile Error: Option already set: TestMethod "
@isTest static testmethod void testDoPost(){ RestRequest req = new RestRequest(); RestResponse res = new RestResponse(); req.requestURI = 'https://XXXX.salesforce.com/services/apexrest/v.1/leads/'; req.httpMethod = 'POST'; RestContext.request = req; RestContext.response = res; RestContext.request.addHeader('firstname','Wain','lastname','Rolen'); String results = LeadRestSvc.doPost(); }
Also, am I supposed to hardcode the requestURI? It seems that the unit test won't work when I try to move this code into my production environment.
I appreciate the assistance!
Hi,
Try to remove the "@isTest" annotation, as my understand and practice, if we have the "testmethod" we can aovid use "@isTest" annotation on method.
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_annotation_isTest.htm
Thannk you!
Thank you, JIE!
Now I'm getting the following error on the last line of the unit test: Method does not exist or incorrect signature: LeadRestSvc.doPost(String, String)
any suggestions?
Thank you
Hi mandyc,
Actually, I just invoke the rest apex method from my external java project. So I can't ensure how to invoke it from another apex test class. But I think there will be some similar between them.
As your know, the rest apex will intercept the request whitch has the following url "/v.1/leads/*", but in your test method, you didn't sent any request, you just set some attribute to a RestResquest instance.
Then you call your doPost method directly.
You can use HTTP method(apply by Salesforce) to send your request.
See an example:
I do the same thing in my java code, I use the HttpClient class to send request to my rest apex.
Thank you!