I am currently working on unit tests for the following method:
@HttpGet
global static REST_MemberRestServiceReturnClass doGet()
{
String[] uriKeysArray = RestContext.request.requestURI.split('/');
String memberName = uriKeysArray.get(uriKeysArray.size()-3); // Get the member name from the uri
List <Contact> contactList = null;
// do awesome programming stuff here and catch any exceptions
try
{
contactList = [ SELECT id FROM Contact WHERE member_name__c = :memberName ];
if (Test.isRunningTest() && (memberName == 'ThrowException')) { throw new REST_MemberRestServiceException('Exception Test'); }
}
catch (Exception e) { return new REST_MemberRestServiceReturnClass ('false', e.getMessage(), null); }
return new REST_MemberRestServiceReturnClass('true', 'Query executed successfully.', contactList);
}
To test against the exception, I wrote the following testMethod:
private static void doGetTestFail (Integer numberOfmembers)
{
String memberName = 'ThrowException';
RestContext.request = setRestRequest(memberName); // pass the request and response objects to the method
RestContext.response = (new RestResponse());
REST_MemberRestServiceReturnClass results = REST_MemberRestService.doGet();
System.assertEquals('false', results.success);
System.assert(results.message.contains('exception'));
}
When I run this test, it passes, but Force.com IDE still tells me that line 21 (the one with the actual Exception) is not covered. But if this were the case, how would the test pass? And, more importantly, how can I successfully cover it?
Also, is there a better way to test this so I don't have to check if Test.isRunning? (e.g. can I somehow sabotage the results in my setup?)