+ Start a Discussion
Peter McGavinPeter McGavin 

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

Hi,

I am getting the error: 09:59:02:052 FATAL_ERROR System.QueryException: List has no rows for assignment to SObject when trying to complete the Apex Web services challenge.

Here is my code:

a) AccountManager class:
====================

@RestResource(urlMapping='/Accounts/*/Contacts')
global class AccountManager {
    @HttpGet
    global static Account getAccount() {
        RestRequest request = RestContext.request;
        String AccId = request.requestURI.substringBetween('/Accounts/' , '/Contacts');
        Account result =  [SELECT Id, Name, (Select Id, Name from Contacts) FROM Account WHERE Id = :AccId];
        return result;
    }
}


b) AccountManagerTest:
===================
@isTest
private class AccountManagerTest {

    private static testMethod void getAccountTest1() {
        Id recordId = createTestRecord();
        System.debug('record id = ' + recordId);
        // Set up a test request
        RestRequest request = new RestRequest();
        request.requestUri = 'https://cunning-bear-27155-dev-ed.my.salesforce.com/services/apexrest/Accounts/'+ recordId +'/contacts' ;
        request.httpMethod = 'GET';
        RestContext.request = request;
        // Call the method to test
        Account thisAccount = AccountManager.getAccount();
        // Verify results
        System.assert(thisAccount != null);
        System.assertEquals('Test record', thisAccount.Name);
        
    }

    // Helper method
    static Id createTestRecord() {
        // Create test record
        Account TestAcc = new Account(
            Name='Test record');
        insert TestAcc;
        Contact TestCon= new Contact(
            LastName='Test', 
            AccountId = Testacc.id);
        insert TestCon;
        return TestAcc.Id;
    }      
}
 
Best Answer chosen by Peter McGavin
Gokula KrishnanGokula Krishnan

All Answers

Gokula KrishnanGokula Krishnan
This was selected as the best answer
Peter McGavinPeter McGavin
Thanks Gokula.