1

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.

3
  • If you're running tests using the Salesforce CLI, then you should run 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 the AccountManager class, then click the "Code Coverage: None" dropdown, select "All Tests", and you'll see the uncovered lined highlighted in red.
    – Derek F
    Aug 28, 2023 at 23:33
  • Only the return statement is showing red. I did notice that the log shows an error "List has no rows for assignment to SObject". No sure what this means. When I ran the query using query editor, it returns an account with 3 contacts. I also verified the endpoint through Workbench. The same account/contacts info is returned successfully. Aug 28, 2023 at 23:54
  • That error message happens because SOQL always returns a List<SObject>. Salesforce is nice enough to let us assign the result of a query to a single SObject 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).
    – Derek F
    Aug 29, 2023 at 0:42

1 Answer 1

1

Because of Isolation of Test Data from Organization Data in Unit Tests, your test cannot access production data. For this reason, you should instead create any test data you need prior to using it.

Account testAccount = new Account(Name='Get Cloudy');
insert testAccount;
Id id = testAccount.Id;
// ... continue your test

Note that some objects are accessible, such as users, so please read the documentation above for exceptions to this rule.

The reason you had 83% coverage is because the line that queries the account record has no rows returned because of database isolation, so the test would fail with:

System.QueryException: List has no rows for assignment to SObject

The last line, return acct would be the line that was uncovered.

2
  • 1
    And as a general tip, if you ever find yourself hard-coding record Ids in any code (test or otherwise), that's a good time to stop and re-evaluate what you're doing. Hard-coded Ids are a bad idea, and it makes it very likely that your code will fail or misbehave when you deploy it to another org. There is some nuance there that I've skipped over, but this isn't the time/place to go into that further.
    – Derek F
    Aug 28, 2023 at 23:42
  • Not only it worked; your explanations make perfect sense. Thank you guys so much!! Aug 29, 2023 at 0:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .