I'm trying to complete the Apex Web Services Trailhead module, but am having some difficulties.

The code I've written appears to function correctly when I access it via Workbench, but I can't persuade my unit tests to pass.

My SUT class is like this:

global class AccountManager {
    global static Account getAccount()
        RestRequest req = RestContext.request;

        String accId = req.requestURI.substringBetween('Accounts/', '/contacts');


        return getAccountById(accId);

    public static Account getAccountById(string account_id)
        Account acc = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) 
                       FROM Account WHERE Id = :account_id];

        return acc;

When I call this via Workbench, the response looks sane:

Screenshot of Workbench

My test looks like this:

@isTest static void TestGetAccountById() {
    RestRequest request = new RestRequest();
    request.requestUri = 'https://playful-raccoon-288300-dev-ed.my.salesforce.com/services/apexrest/Accounts/0011r00001nUpkgAAC/contacts';
    request.httpMethod = 'GET';
    RestContext.request = request;
    // Call the method to test
    Account thisAcc = AccountManager.getAccount();

    // Verify results
    System.assert(thisAcc != null);
    System.assertEquals('Bluebeards Grog House', thisAcc.Name);

The exception I'm getting is:

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

I understand from my research that this means that the query is returning 0 rows. This confuses me because the account ID being passed is the same as the one I'm using in Workbench. I wondered if my logic for extracting the account ID was wonky, but I've been able to verify this using checkpoints.

Am I missing something very obvious?

  • This is a dupe. Sorry! I did search, but didn't find the other question. The accepted answer on it solved my issue though, so thanks!
    – Tom Wright
    Commented Apr 4, 2018 at 16:08
  • 2
    Admittedly, it's pretty hard to find, but it has been asked a few times. Glad I could help you out!
    – sfdcfox
    Commented Apr 4, 2018 at 16:09


Browse other questions tagged .