+ Start a Discussion
mandycmandyc 

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!

WEN JIEWEN JIE

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!

mandycmandyc

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?

 

    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;
        String results = LeadRestSvc.doPost('Wain','Rolen');       
    } 

 

Thank you

WEN JIEWEN JIE

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.

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;

Then you call your doPost method directly. 

You can use HTTP method(apply by Salesforce) to send your request.

See an example:

public class HttpCalloutSample {

// Pass in the endpoint to be used using the string url 
    
  public String getContent(String url) {

// Instantiate a new http object 
    
    Http h = new Http();

// Instantiate a new HTTP request, specify the method (GET) as well as the endpoint 
    
    HttpRequest req = new HttpRequest();
    req.setEndpoint(url);
    req.setMethod('GET');

// Send the request, and return a response 
    
    HttpResponse res = h.send(req);
    return res.getBody();
  }
}

 

I do the same thing in my java code, I use the HttpClient class to send request to my rest apex.

 

Thank you!