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
Dagny FernandesDagny Fernandes 

Unit Tests for Apex REST Services

I have a REST service but i am not able to cover this class. 
Below is my code, need help ASAP.

Thanks You in advance.
@RestResource(urlMapping='/AttachPDF/*')
global class ServiceInvoiceRedirectController {
	
	@HttpGet
        global static void AttachPDFtoRecordREST() {
        	List<Id> accId = new List<Id>();
        	List<String> emailList = new List<String>();
            RestRequest req = RestContext.request;
            id recordId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

            PageReference pdfPage = new PageReference('/apex/ServiceInvoicePDF?Id='+recordId);
            pdfPage.getParameters().put('id',recordId);
            Blob pdf = pdfPage.getContentAsPdf(); //!Test.isRunningTest() ? pdfPage.getContentAsPdf() : Blob.ValueOf('dummy text');
            
			//List of accoutn Id's of related project
            for(Account_Project_Junction__c accPrjJunRec: [SELECT Id,Project__c,Account__c From Account_Project_Junction__c WHERE Project__c =: recordId]){
            	accId.add(accPrjJunRec.Account__c);
            }
            
            //List of email id's of the selected account's
            for(Contact conRec: [SELECT Id,AccountID,Email,Is_Primary_Contact__c From Contact where AccountID IN: accId AND Is_Primary_Contact__c = true]){
            	if(conRec.Email != null){
            		emailList.add(conRec.Email);
            	}
            }
            
            Project__c prjRec = [Select Id,Name from Project__c where Id =: recordId];
            //Insert Invoice record for related project
	        Invoice__c invoRec = new Invoice__c();
	        invoRec.RecordTypeId = Constants_PicklistVariables.serInvoice; 
	        invoRec.Project__c = recordId;
	        
	        try{
	        insert invoRec;
	        }catch(Exception e){
	            System.debug('Invoice=Exception-->'+e);
	        }
	        System.debug('Invoice=invoRec.id-->'+invoRec);
	        
	        //Insert Attacment to the invoice        
	        Attachment a = New Attachment();
	        a.body = pdf;
	        a.parentID = invoRec.id;
	        a.ContentType  = 'application/pdf';
	        a.Name = 'SER-INV-'+invoRec.id+'.pdf';
	        try{
	        insert a;
	        }catch(Exception e){
	            System.debug('Attachment=Exception-->'+e);
	        }
	        
	        //Create the email attachment
	    	Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
	    	efa.setFileName('SER-INV-'+invoRec.id+'.pdf');//Pleace ad pdf name from contact name project and oppty concatinate 
		    efa.setContentType('application/pdf');
		    efa.setBody(pdf);
		    
		    // Create the Singal Email Message
		    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
		    email.setSubject('Service Invoice Notification');
		    String[] CCEmails = emailList;
			email.setToAddresses(CCEmails);
		    //email.setToAddresses(new String[] { 'developer@extentor.com' });//add Contact email id
		    email.setPlainTextBody( 'Dear:Sir/Madam <br/> Please Find Attachment your financial report Attached with this email.');
		    email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
		    
		    // Sends the email
		    Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            
        }

        // call this method from your Batch Apex
        global static void attachPdfToRecord( Id recordId, String sessionId )
        {
        	System.debug('recordId==>'+recordId);
        	System.debug('sessionId==>'+sessionId);
        	System.debug('Iam in REST API Call method');
            HttpRequest req = new HttpRequest();
            req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/apexrest/AttachPDF/'+recordId);
            req.setMethod('GET');
            req.setHeader('Authorization', 'OAuth ' + sessionId);

            Http http = new Http();
            HttpResponse response = http.send(req);    
        }
        
}

Test class:
@isTest(seeAllData=false)
global class Test_ServiceInvoiceRedirectController{
   
    static testMethod void testDoGet() {
		Account acc= InitialTestData.createAccount('Raj');
        insert acc;
        
        Contact contact1=InitialTestData.createContact(acc.id,'Sen','raj@gmail.com');
        insert contact1;
        
        Opportunity_Deal__c oppdeal=InitialTestData.createOpportunityDeal('Opp1',acc.id,contact1.id,false,'Quote');
        insert oppdeal;
        
        Project__c project1=InitialTestData.createPlotProject('Pro',acc.id,'Submitted',oppdeal.id);
        insert project1;
        
    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    // pass the req and resp objects to the method     
    req.requestURI = URL.getSalesforceBaseUrl().toExternalForm()+'/services/apexrest/AttachPDF/'+project1.Id;  
    req.httpMethod = 'GET';

    ServiceInvoiceRedirectController.attachPdfToRecord results = ServiceInvoiceRedirectController.AttachPDFtoRecordREST(req,res);

    System.assertEquals('true', results.success);
    System.assertEquals(10, results.records.size());
    System.assertEquals('Query executed successfully.', results.message);

  }
	
}
Best Answer chosen by Dagny Fernandes
Dagny FernandesDagny Fernandes
Thanks a lot @Roy Luo for your help the above code throwing the null value in the response RestRequest req = RestContext.request; req was null but it coverd the attachPdfToRecord method. this helped a lot to complet the code coverage below is the complete test code 

the importent was the "req" url gives the record id to get that id was importent*

Mock Test Class:(The same code)
 
@isTest
public class Test_MockAttachPDFtoRecordHttpResponce implements HttpCalloutMock 
{

        public HTTPResponse respond(HTTPRequest req) 
        {  
                // Create a fake response
                HttpResponse res = new HttpResponse();
                
                return res;
        }
}



Test Class
@isTest(seeAllData=false)
private class Test_ServiceInvoiceRedirectController{
    
    static Account testAccount;
    static Contact testContact;
    static Opportunity_Deal__c testOpportunity;
    static Project__c testNewProject;
    static User testUser;
    
	
    Static void init(){
        
        //Account
        testAccount = InitialTestData.createAccount('TestAccount');
        insert testAccount;
        //Contact
        testContact = InitialTestData.createContact(testAccount.Id,'TestName','testContact@eamil.com');
        insert testContact;
        //User
        testUser = InitialTestData.createUser('TestLast', 'TestFirst', 'userProfile@testuser.com', 'System Administrator');
        insert testUser;
        //Opportunity
        testOpportunity = InitialTestData.createOpportunityDeal('TestOpportunity', TestAccount.Id, testContact.Id, False, 'Presentation');
        insert testOpportunity;
        //Project
        testNewProject = InitialTestData.createNewProject('testProject',TestAccount.Id,'Verified',testOpportunity.Id);
        insert testNewProject;
     }
    
    static testMethod void attachPdfToRecord()
    {
        init();
        Test.startTest();
        
        //mock up your test data
		Test.setMock(HttpCalloutMock.class, new Test_MockAttachPDFtoRecordHttpResponce()); 
		String sessionId=UserInfo.getSessionId();
        ServiceInvoiceRedirectController.attachPdfToRecord(testNewProject.Id, sessionId); 
        Test.stopTest();

    }
    
    static testMethod void AttachPDFtoRecord_Test()
    {
        init();
        Test.startTest();
        RestRequest req = new RestRequest(); 
    	RestResponse res = new RestResponse();
        
        req.requestURI = '/services/apexrest/AttachPDF/';  
        req.addParameter('recordId', testNewProject.id);
    	req.httpMethod = 'GET';  
        RestContext.request = req;
    	RestContext.response = res;
        ServiceInvoiceRedirectController.AttachPDFtoRecordREST();
        
    }
        
}

 

All Answers

Roy LuoRoy Luo
You need to mock response for unit test. Try something like this:
 
@isTest
public class MockAttachPDFtoRecordHttpResponse implements HttpCalloutMock 
{

        public HTTPResponse respond(HTTPRequest req) 
        {  
                // Create a fake response
                HttpResponse res = new HttpResponse();
                //res.setHeader('Content-Type', 'application/text');
                //String body = 'response content here';  
                //res.setBody(body);             
                //res.setStatusCode(200);
                return res;
        }
}
 
@isTest
private class Test_ServiceInvoiceRedirectController
{
    static testMethod void AttachPDFtoRecord_Test()
    {
        Test.startTest();
        //mock up your test data

        Test.setMock(HttpCalloutMock.class, new MockAttachPDFtoRecordHttpResponse());
        ServiceInvoiceRedirectController.AttachPDFtoRecordREST(); 
        Test.stopTest();

        //do your assertion here
       
    }
     
}

 
Dagny FernandesDagny Fernandes
Thanks a lot @Roy Luo for your help the above code throwing the null value in the response RestRequest req = RestContext.request; req was null but it coverd the attachPdfToRecord method. this helped a lot to complet the code coverage below is the complete test code 

the importent was the "req" url gives the record id to get that id was importent*

Mock Test Class:(The same code)
 
@isTest
public class Test_MockAttachPDFtoRecordHttpResponce implements HttpCalloutMock 
{

        public HTTPResponse respond(HTTPRequest req) 
        {  
                // Create a fake response
                HttpResponse res = new HttpResponse();
                
                return res;
        }
}



Test Class
@isTest(seeAllData=false)
private class Test_ServiceInvoiceRedirectController{
    
    static Account testAccount;
    static Contact testContact;
    static Opportunity_Deal__c testOpportunity;
    static Project__c testNewProject;
    static User testUser;
    
	
    Static void init(){
        
        //Account
        testAccount = InitialTestData.createAccount('TestAccount');
        insert testAccount;
        //Contact
        testContact = InitialTestData.createContact(testAccount.Id,'TestName','testContact@eamil.com');
        insert testContact;
        //User
        testUser = InitialTestData.createUser('TestLast', 'TestFirst', 'userProfile@testuser.com', 'System Administrator');
        insert testUser;
        //Opportunity
        testOpportunity = InitialTestData.createOpportunityDeal('TestOpportunity', TestAccount.Id, testContact.Id, False, 'Presentation');
        insert testOpportunity;
        //Project
        testNewProject = InitialTestData.createNewProject('testProject',TestAccount.Id,'Verified',testOpportunity.Id);
        insert testNewProject;
     }
    
    static testMethod void attachPdfToRecord()
    {
        init();
        Test.startTest();
        
        //mock up your test data
		Test.setMock(HttpCalloutMock.class, new Test_MockAttachPDFtoRecordHttpResponce()); 
		String sessionId=UserInfo.getSessionId();
        ServiceInvoiceRedirectController.attachPdfToRecord(testNewProject.Id, sessionId); 
        Test.stopTest();

    }
    
    static testMethod void AttachPDFtoRecord_Test()
    {
        init();
        Test.startTest();
        RestRequest req = new RestRequest(); 
    	RestResponse res = new RestResponse();
        
        req.requestURI = '/services/apexrest/AttachPDF/';  
        req.addParameter('recordId', testNewProject.id);
    	req.httpMethod = 'GET';  
        RestContext.request = req;
    	RestContext.response = res;
        ServiceInvoiceRedirectController.AttachPDFtoRecordREST();
        
    }
        
}

 
This was selected as the best answer