Can I use SystemApex Rest returns 200 OK status code when directly access its Rest endpoint.runAs to test However, in Apex Rest classes with different users?test class. RestResponse hooked in RestContext does not contains the status code (see below debug log).
@isTest
static void testCreateUser() {
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
TestUtil.initTestData();
User customerAdmin = [SELECT Id, AccountId FROM User WHERE username = '[email protected]'];
String requestBody = '{ "firstName": "Test", "lastName": "Case 2", "email": "[email protected]" }';
req.requestURI = URL.getSalesforceBaseUrl() + '/services/apexrest/MyId';
req.httpMethod = 'POST';
req.requestBody = Blob.valueOf(requestBody);
Test.startTest();
RestContext.request = req;
RestContext.response = res;
System.runAs(customerAdmin) {
UserManagementRestController.createMyId();
System.debug(RestContext.requestreq);
System.debug(RestContext.responseres);
}
Test.stopTest();
// Seems that Salesforce does notSomething supportgoes mixingwrong Systemhere.runAs and RestContext, noNo content in RestContext.response
// Tempoary disable assertion on response
//System.assertEquals(200, res.statusCode);
List<User> users = [SELECT FirstName, LastName, Username, AccountId FROM User WHERE Email = '[email protected]'];
System.assertEquals(1, users.size());
User u = users[0];
System.assertEquals('Test', u.FirstName);
System.assertEquals('Case 2', u.LastName);
System.assertEquals('[email protected]', u.Username);
System.assertEquals(customerAdmin.AccountId, u.AccountId);
}
In the debug log we can see the RestRequest is correctly set. However the RestResponse does not have any value in it. Would expect statusCode=200
I am wondering if Salesforce supports mixing System.runAsSo what is the reason of getting different result from the test class and RestContext in the Apexactual Rest unit test. I needendpoint? Any way to test the exact behaviour of the restApex Rest endpoint with different users. Is there any other way to goin a unit test class?