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
ericmonteericmonte 

APEX REST Unit Test Question

hey guys can someone help me write a unit test for my try catch block? I am able to get 82% of my APEX Rest, but having a hard time covering the catch line.

 

@RestResource(urlMapping='/getofflinedata/*')
global class WS_RestGetOfflineData {
	
	@HttpGet
	
	global static List <Address__c> queryAddres(){
		try{
			//Request and response parameters to and from the external client
			RestRequest req = RestContext.request;
			Restresponse res = RestContext.response;
			
			List<string> stringAccType= new List <String>();
			stringAccType.add('Some Values');
			
			// Query the Address object and return all records that meet the criteria in a List
			List <Address__c> addList = new List <Address__c>();
			
			addList = [select id, Name
			from Address__c 
			where AddType in: (stringAccType) Limit 5000];
			
			return addList;
			
		} catch (System.Queryexception ex){
			// throw query exception to external message.
			throw ex;
		}
	}
	

 and my test method so far:

static testmethod void testGetOfflineData(){
		try{
			RestRequest req = new RestRequest(); 
			RestResponse res = new RestResponse();
	 
			req.requestURI = 'https://cs10.salesforce.com/services/apexrest/getofflinedata/';  
			req.httpMethod = 'GET';
			RestContext.request = req;
			RestContext.response = res;
			
			
			List <Address__c> addList = WS_RestGetOfflineData.queryAddres();
		} catch (System.Queryexception ex){
			throw ex;
		}
			
	}

 

Also when I deploy this to my production what req.RequestURI should i embedd?

can i just do : req.requestURI = '/services/apexrest/getofflinedata/'; ?

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
ReidCReidC

Why are you catching the exception here?

 

According to the docs, that exception represents -- Any problem with SOQL queries, such as assigning a query that returns no records or more than one record to a singleton sObject variable.

 

And you're not doing that -- you're assigning to a list.

All Answers

ReidCReidC

Why are you catching the exception here?

 

According to the docs, that exception represents -- Any problem with SOQL queries, such as assigning a query that returns no records or more than one record to a singleton sObject variable.

 

And you're not doing that -- you're assigning to a list.

This was selected as the best answer
ericmonteericmonte

You are right. An oversight on my part. I guess I can just use an if statement or throw a custom exception.

 

Thanks