How to login salesforce users programmatically?

999    Asked by amit_2689 in QA Testing , Asked on Jul 19, 2021

I require to login certain users among the test users created in test classes.

Each user is created as follows:

User user = new User(Alias='test', Email='test@none.com'); insert user;
I create multiple such sample users.
My business logic class checks for logged in users via:
List sessions = [Select UserId From AuthSession];

UserId in this list tells me which users are logged in. How can I login my user programmatically in my test case? Edit: I run a scheduled Apex class which assigns a particular lead from a Queue to one among list of users. Scheduler runs as Admin. It needs to check which among UserA, UserB or UserC is Logged in. To make this check I use AuthSession to determine which users are logged in. UserInfo contains information about Admin which is irrelevant. Under this light is there alternative to AuthSession? In test case, I create mock users and need to simulate some among them are logged in. So that I can test if my business logic works well to skip assignment for 'Not logged in users'.

Answered by Angela Baker

The System.runAs() method allows you to establish a new user session in unit test context. To adapt the example in the linked documentation,



        @isTest public static void testRunAs() { String uniqueUserName = 'standard user' + DateTime.now().getTime() + '@testorg.com'; Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; User u = new User( Alias = 'standt', Email='standarduser@testorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName=uniqueUserName ); System.runAs(u) { System.assertEquals(u.Id, UserInfo.getUserId(), 'running as new user'); } }
        As far as I can tell, however, it doesn't work with the AuthSession sObject. Doing
        System.debug('AuthSession.UsersId = ' + [SELECT UsersId FROM AuthSession]);

inside a System.runAs() block returns no rows. That leaves a couple of approaches for you: Use UserInfo.getUserId() instead of querying AuthSession. (I'm not sure what reasons led you to utilize the Object, so I don't know if this is workable or not). Use a dependency-injection approach to mock the query. This might require extensive rework of your code, and we can't see enough in your question to be sure.

Edit- Multiple user scenario

You are not going to be able to have multiple users logged in during a unit test. Instead, you will have to take approach (2) above and factor your query against AuthSession into a dependent class. You'll then need to utilize dependency injection in the test context to provide a mock implementation so that you can directly control the data returned to the class being tested.7879



Your Answer

Interviews

Parent Categories