I need to cover the below method where I am using the current logged in user in the query.

public static User getUserInformation()    
    User user1 = new User();  
    user1 = [Select Id, Dom__c from User where id=: userinfo.getUserId()];  
    return user1;   
  • 1
    would it not always run because test class will run by a logged in user always? so everytime userinfo would return a row...? – Ayub Jan 8 '19 at 16:39

Unit tests have a running user, too, just like any Apex code. If you were to write a unit test that called this method, e.g.

public static void does_query_current_user() {
    System.assertEquals(UserInfo.getUserId(), myClass.getUserInformation().Id, 'got the right user');

and then go into your IDE or Developer Console and ask to run the test, you would be the running user. UserInfo.getUserId() would return your user Id, and the query would find your user record.

In some situations, you'll be testing code that is dependent on who the running user is (this code is not). In those situations, your unit test will often need to create and insert its own User record that has the correct role and profile, and then invoke the code that's being tested within a System.runAs() block:

User myTestUser = UserFactory.createTestUser();
System.runAs(myTestUser) {
    System.assertEquals(UserInfo.getUserId(), myClass.getUserInformation().Id, 'got the right user');

Then, the running user inside the runAs block will be myTestUser, and that user's Id will be returned for UserInfo.getUserId().

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.