This is to reference with Salesforce Apex REST Services Trailhead
Create an Apex REST service that returns an account and it's contacts.
Scenario: Create an Apex REST class that is accessible at '/Accounts//contacts'. The service will return the account's ID and Name plus the ID and Name of all contacts associated with the account. Write unit tests that achieve 100% code coverage for the class and run your Apex tests.
Code:
@RestResource(urlMapping='/Accounts/*/contacts')
global with sharing class AccountManager {
@HttpGet
/*
global static List<Contact> getAccount() {
RestRequest req = RestContext.request;
String accId = req.requestURI.substringBetween('Accounts/', '/contacts');
Account acc = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account WHERE Id = :accId];
system.debug(acc);
system.debug(acc.Contacts);
return acc.Contacts;
}
*/
global static Account getAccount() {
RestRequest req = RestContext.request;
String accId = req.requestURI.substringBetween('Accounts/', '/contacts');
Account acc = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account WHERE Id = :accId];
system.debug(acc);
system.debug(acc.Contacts);
return acc;
}
}
Test Class:
@IsTest
private class AccountManagerTest{
@isTest static void testAccountManager() {
Id recordId = createTestRecord();
Contact Cont1 = new Contact();
objCont.LastName = 'ABC';
objCont.AccountId = recordId ;
insert Cont1;
Contact Cont2 = new Contact();
objCont2.LastName = 'XYZ';
objCont2.AccountId = recordId ;
insert Cont2 ;
RestRequest request = new RestRequest();
request.requestUri =
'https://na1.salesforce.com/services/apexrest/Accounts/'+recordId+'/contacts';
request.httpMethod = 'GET';
RestContext.request = request;
Account lst = AccountManager.getAccount();
/* Tried to return Contact List but failed Trailhead Verification
List<Contact> lst = new List<Contact>();
lst = AccountManager.getAccount();
*/
}
static Id createTestRecord() {
Account accTest = new Account(Name='Test Record');
insert accTest ;
return accTest.Id;
}
}
I tried to verify with this apex class(code coverage 100%) but verification is failing. So I had tried to return "acc.Contacts"(which is commented in my class). Still verification is failing.
Please guide me where I am going wrong.
Best Answer
Kindly Update test class AccountManagerTest. Also add base url in Remote Site Settings.