I can't seem to figure out how to reach 100% code coverage. Currently, I'm at 80% and the "return acct;" is the only thing that is not covered. Could somebody help me figure out how to test this?
The error/fail in debug is:
"System.QueryException: List has no rows for assignment to SObject"
and the Stack Trace is:
"Class.AccountManager.getAccount: line 10, column 1
Class.AccountManagerTest.testGetAccount: line 11, column 1"
ACCOUNT MANAGER CLASS:
@RestResource (urlMapping = '/Account/*/contacts')
global with sharing class AccountManager
{
@HttpGet
global static Account getAccount ()
{
RestRequest request = RestContext.request;
String accountId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
//Account acct = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account WHERE Id = :accountId];
Account acct = [SELECT Id, Name FROM Account WHERE Id = :accountId];
return acct;
}
}
ACCOUNT MANAGER TEST:
@isTest
private class AccountManagerTest
{
@isTest static void testGetAccount ()
{
Id recordId = createTestRecord ();
RestRequest request = new RestRequest ();
request.requestUri = 'https://yourInstance.salesforce.com/services/apexrest/Accounts/' + recordId + '/contacts';
request.httpMethod = 'GET';
RestContext.request = request;
Account thisAccount = AccountManager.getAccount();
System.assert (thisAccount != null);
System.assertEquals ('Test Record', thisAccount.Name);
}
static Id createTestRecord ()
{
Account testAccount = new Account (Name = 'Test Record');
insert testAccount;
Contact testContact = new Contact (AccountId = testAccount.Id);
return testAccount.Id;
}
}
Thank you!
Best Answer
Your code looks for the Id thus:
You set the URI thus:
So your code is filtering:
Change your URI to remove
+ '/contacts'
.