Just get started with Trailhead but got stuck with one challenge. It requires you to write an apex class to implement a REST GET service to retrieve an account and associated contacts. Then you have to write a test case to test. The issue is with test coverage. It always reports 83% code coverage. I am puzzled why it's not 100% as required. Which line of code is not covered by the test class?
Here is the getAccount service class
// accessible at /Accounts/<Account_ID>/contacts
@RestResource(urlMapping='/Accounts/*')
global with sharing class AccountManager {
@HttpGet
global static Account getAccount() {
RestRequest request = RestContext.request;
String str = request.requestURI.substring(0, request.requestURI.lastIndexOf('/'));
String acctId = str.substring(str.lastIndexOf('/')+1);
Account acct = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account WHERE Id = :acctId];
return acct;
}
}
And here is the test class:
@IsTest
public class AccountManagerTest {
@isTest static void testGetAccount() {
String id = '0018b00002VulQKAAZ';
RestRequest request = new RestRequest();
request.requestUri = 'https://my-dev-ed.trailblaze.my.salesforce.com/' +
'services/apexrest/Accounts/' + id + '/contacts';
request.httpMethod = 'GET';
RestContext.request = request;
// call the method to test
Account thisAcct = AccountManager.getAccount();
// verify the results
System.assert(thisAcct != null);
System.assertEquals('Get Cloudy', thisAcct.Name);
}
}
Any help would be greatly appreciated.
sf apex run test
with the-c
flag to get information about code coverage. If you're running tests through the Developer Console, then you can run the test from there, open theAccountManager
class, then click the "Code Coverage: None" dropdown, select "All Tests", and you'll see the uncovered lined highlighted in red.List<SObject>
. Salesforce is nice enough to let us assign the result of a query to a singleSObject
instance (Account
in your case) when the query returns exactly one row. If it returns 0 rows or 2+ rows, you'll get an error (List has no rows/more than one row for assignment to SObject).