function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sujithkumar j 9sujithkumar j 9 

Help to get code coverage for rest class

@Restresource(urlmapping='/Lead/*')

     global class Cls_LeadData
    {
  @HttpPost
    global static void updateLead(String codeid, String Zipid, String Email) {
    RestRequest req = RestContext.request;
    RestResponse res = RestContext.response;
   
        res.addHeader('Access-Control-Allow-Origin','*');
    res.addHeader('Content-Type', 'application/json');
    res.addHeader('Access-Control-Allow-Credentials','true');
    res.addHeader('Access-Control-Allow-Headers','x-requested-with, Authorization');
    res.addHeader('Accept-Type', 'application/json');
    res.addHeader('Access-Control-Allow-Headers','Content-Type, Accept');
    res.addHeader('Access-Control-Allow-Headers','POST');
    res.addHeader('Access-Control-Allow-Methods', 'POST');
    RestContext.response.addHeader('Content-Type', 'application/json');
        
       try {
           CodeID__c Code = null;        
           String LeadJson = '';
           try{
               CodeID__c LeadDetail= [SELECT Lead__r.Id, Name, Lead__r.PostalCode, Lead__r.Email  FROM CodeID__c where Name=:codeid And Lead__r.PostalCode=:Zipid And Lead__r.Id != null Limit 1];
               Lead ld = new Lead();
               ld.Id = LeadDetail.Lead__r.Id;
               ld.Email = Email;    
                //Update Lead if Exists   
                Update ld;
            Lead led = [Select Name,Street,City,State,Country,PostalCode,Email,UniqueID__c, Lender__c From Lead Where Id=:ld.Id Limit 1];
            Cls_LeadConvertAftertrigger.LeadConvertMethod(LeadDetail.Lead__r.Id);
            LeadJson = JSON.serializePretty(led);              
            RestContext.response.responseBody = Blob.valueOf(LeadJson);            
        } catch(Exception ex){
            RestContext.response.responseBody = Blob.valueOf('{ "valid" : false }'); 
        }
    }
    catch(Exception e) {
            RestContext.response.responseBody = Blob.valueOf('{ "valid" : false }'); 
        }
        }
    }

Here is my test class

@istest
public class Cls_LeadData__test { static testMethod void testupdateLead() {
//CodeID__c m= Lead l=new Lead();
l.firstname='testname';
l.lastname='test';
l.company='Test Company';
//l.CodeID__c='90876544';
l.email='sample@test.com';
l.phone='6884382997';
l.street='123 Test Ave';
l.city='Somewhere';
l.state='MA';
l.PostalCode='87945';
l.country='US';
String JSONMsg= JSON.serialize(l);
RestRequest req = new RestRequest();
req.addHeader('Content-Type', 'application/json'); // Add a JSON Header as it is validated
req.requestURI = '/services/apexrest/Lead/';
req.httpMethod = 'POST';
req.requestBody = Blob.valueof(JSONMsg); // Add JSON Message as a POST
RestResponse res = new RestResponse();
RestContext.request = req;
RestContext.response = res;
Cls_LeadData.updateLead('90876544','87945','sample@test.com');
} }
I am getting 65% code coverage..I am not able to get above 75% code coverage. Can any one help me how to get code coverage for the above class.

 
Best Answer chosen by sujithkumar j 9
Amit Chaudhary 8Amit Chaudhary 8
Issue was coming due to below line and you are fatching Unknown Unknown Account.
account acc = [select id,name from account where name = 'Unknown Unknown' limit 1];
So please create same account in test class also
@istest
public class Cls_LeadData__test 
{ 
	static testMethod void testupdateLead() 	
	{
		Account acc=new Account();
		acc.Name ='Unknown Unknown';
		insert acc;
	
		Lead l=new Lead();
			l.firstname='testname';
			l.lastname='test';
			l.company='Unknown Unknown';
			l.email='sample@test.com';
			l.phone='6884382997';
			l.street='123 Test Ave';
			l.city='Somewhere';
			l.state='MA';
			l.PostalCode='87945';
			l.country='US';
		insert l;
		
		CodeID__c code = new CodeID__c();
			code.Name = '90876544';
			code.Lead__c=l.id;
			// add all required field
		insert code;
		
		String JSONMsg= JSON.serialize(l);
		RestRequest req = new RestRequest();
		req.addHeader('Content-Type', 'application/json'); // Add a JSON Header as it is validated
		req.requestURI = '/services/apexrest/Lead/';
		req.httpMethod = 'POST';
		req.requestBody = Blob.valueof(JSONMsg); // Add JSON Message as a POST
		RestResponse res = new RestResponse();
		RestContext.request = req;
		RestContext.response = res;
		
		Cls_LeadData.updateLead('90876544','87945','sample@test.com');
		
	} 

}


Let us know if this will help you

Thanks
Amit Chaudhary
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please update your API class like below.
NOTE:- I found one extra try catch
global class Cls_LeadData
    {
		@HttpPost
		global static void updateLead(String codeid, String Zipid, String Email) 
		{
			RestRequest req = RestContext.request;
			RestResponse res = RestContext.response;
   
			res.addHeader('Access-Control-Allow-Origin','*');
			res.addHeader('Content-Type', 'application/json');
			res.addHeader('Access-Control-Allow-Credentials','true');
			res.addHeader('Access-Control-Allow-Headers','x-requested-with, Authorization');
			res.addHeader('Accept-Type', 'application/json');
			res.addHeader('Access-Control-Allow-Headers','Content-Type, Accept');
			res.addHeader('Access-Control-Allow-Headers','POST');
			res.addHeader('Access-Control-Allow-Methods', 'POST');
			RestContext.response.addHeader('Content-Type', 'application/json');
        
			try 
			{
			   CodeID__c Code = null;        
			   String LeadJson = '';
			   
			   CodeID__c LeadDetail= [SELECT Lead__r.Id, Name, Lead__r.PostalCode, Lead__r.Email  FROM CodeID__c where Name=:codeid And Lead__r.PostalCode=:Zipid And Lead__r.Id != null Limit 1];

			   Lead ld = new Lead();
			   ld.Id = LeadDetail.Lead__r.Id;
 			   ld.Email = Email;    
				//Update Lead if Exists   
				Update ld;
				Lead led = [Select Name,Street,City,State,Country,PostalCode,Email,UniqueID__c, Lender__c From Lead Where Id=:ld.Id Limit 1];
				Cls_LeadConvertAftertrigger.LeadConvertMethod(LeadDetail.Lead__r.Id);
				LeadJson = JSON.serializePretty(led);              
				RestContext.response.responseBody = Blob.valueOf(LeadJson);            
			}
			catch(Exception e) 
			{
				RestContext.response.responseBody = Blob.valueOf('{ "valid" : false }'); 
			}
        }
    }
Test class
@istest
public class Cls_LeadData__test 
{ 
	static testMethod void testupdateLead() 	
	{
	
		Lead l=new Lead();
			l.firstname='testname';
			l.lastname='test';
			l.company='Test Company';
			l.email='sample@test.com';
			l.phone='6884382997';
			l.street='123 Test Ave';
			l.city='Somewhere';
			l.state='MA';
			l.PostalCode='87945';
			l.country='US';
		insert l;
		
		CodeID__c code = new CodeID__c();
			code.Name = '90876544';
			code.Lead__c=l.id;
			// add all required field
		insert code;
		
		String JSONMsg= JSON.serialize(l);
		RestRequest req = new RestRequest();
		req.addHeader('Content-Type', 'application/json'); // Add a JSON Header as it is validated
		req.requestURI = '/services/apexrest/Lead/';
		req.httpMethod = 'POST';
		req.requestBody = Blob.valueof(JSONMsg); // Add JSON Message as a POST
		RestResponse res = new RestResponse();
		RestContext.request = req;
		RestContext.response = res;
		
		Cls_LeadData.updateLead('90876544','87945','sample@test.com');
		
	} 

}
Please check below post for rest test class.
1) http://amitsalesforce.blogspot.in/2016/04/rest-api-in-salesforce-execute-rest-api.html

Let us know if this will help you

Thanks
Amit Chaudhary
sujithkumar j 9sujithkumar j 9
HI Amit,

             Thanks for your reply. I updated like same.But i am getting exception System.QueryException: List has no rows for assignment to SObject on Class.Cls_LeadConvertAftertrigger.LeadConvertMethod: line 9, column 1. Can you please help me how to resolve this.
Amit Chaudhary 8Amit Chaudhary 8
It look like some issue is coming in Cls_LeadConvertAftertrigger class. Please post the code for Cls_LeadConvertAftertrigger class so that we can help u
sujithkumar j 9sujithkumar j 9
HI Amit,

           Please find the Lead conversion class. We are using this toconvert lead automatically when email will be updated on lead through the api call.

public class Cls_LeadConvertAftertrigger {
    
    @future (callout=true)
    public static void LeadConvertMethod(Id leadId) {
        if(leadId !=null)
        {
        
        Lead l = [select id,name,isconverted,ownerid,company from lead where Id = : leadId limit 1];
        account acc = [select id,name from account where name = 'Unknown Unknown' limit 1];    
        Database.LeadConvert lc = new database.LeadConvert();
        if (l.name!='Unknown Unknown'){
            l.Company=l.name;
           // update l;
        }
             //string str = l.ownerid;
             //str = str.substring(0,4);
             
              if(l.isConverted == false) {        //to prevent recursion   
                  lc.setLeadId(l.id);
                  lc.setDoNotCreateOpportunity(true);
                  if((l.company == 'Unknown Unknown')&&(acc!=null))
                  {
                      lc.setaccountid(acc.id);
                  }
                  lc.setOverwriteLeadSource(true);
                  //if(str == '00Gi')
                   // {
                        lc.ownerId = userinfo.getuserid();
                    //}
                  LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
                  lc.setConvertedStatus(convertStatus.MasterLabel);
                  
                  Database.LeadConvertResult lcr = Database.convertLead(lc);
                  
              }
        }
    }

}

Thanks,
sujith
Amit Chaudhary 8Amit Chaudhary 8
Issue was coming due to below line and you are fatching Unknown Unknown Account.
account acc = [select id,name from account where name = 'Unknown Unknown' limit 1];
So please create same account in test class also
@istest
public class Cls_LeadData__test 
{ 
	static testMethod void testupdateLead() 	
	{
		Account acc=new Account();
		acc.Name ='Unknown Unknown';
		insert acc;
	
		Lead l=new Lead();
			l.firstname='testname';
			l.lastname='test';
			l.company='Unknown Unknown';
			l.email='sample@test.com';
			l.phone='6884382997';
			l.street='123 Test Ave';
			l.city='Somewhere';
			l.state='MA';
			l.PostalCode='87945';
			l.country='US';
		insert l;
		
		CodeID__c code = new CodeID__c();
			code.Name = '90876544';
			code.Lead__c=l.id;
			// add all required field
		insert code;
		
		String JSONMsg= JSON.serialize(l);
		RestRequest req = new RestRequest();
		req.addHeader('Content-Type', 'application/json'); // Add a JSON Header as it is validated
		req.requestURI = '/services/apexrest/Lead/';
		req.httpMethod = 'POST';
		req.requestBody = Blob.valueof(JSONMsg); // Add JSON Message as a POST
		RestResponse res = new RestResponse();
		RestContext.request = req;
		RestContext.response = res;
		
		Cls_LeadData.updateLead('90876544','87945','sample@test.com');
		
	} 

}


Let us know if this will help you

Thanks
Amit Chaudhary
 
This was selected as the best answer
sujithkumar j 9sujithkumar j 9
Hi Amit,
           Thank you very much for your help.Now i am getting 86%  code coverage and only exceptions are not covering. 

Thanks,
sujith
sujithkumar j 9sujithkumar j 9
Hi Amit,
             Can u please help me to how we will cover that exception part also.My manager asking atleast 90% code coverage.
Thanks