0

I have to create a test class that checks for this "if" condition, and I don't know how to set user.Profile.name for test data.

            //System Admin User Id
            string userId = UserInfo.getUserId();
            
            //Get user profile
            User user = [select id, ProfileId, Profile.Name from user where id = :userId];
            
            Config__c Config = [select System_Admin_Id__c from Config__c];
            
            if(user.Profile.Name != 'System Administrator'){
            ...
            }

I have tried this:

            String uniqueUserName = 'user' + DateTime.now().getTime() + '@org.com';
            User user = new User(Username           = uniqueUserName,
                                      Email             = '[email protected]',
                                      LastName          = 'Admin',
                                      ProfileId         = [SELECT Id FROM Profile WHERE Name = 'Standard User' limit 1].Id,
                                      Alias             = 'testUser',
                                      TimeZoneSidKey    = 'Asia/Bangkok',
                                      LocaleSidKey      = 'th_TH',
                                      EmailEncodingKey  = 'UTF-8',
                                      LanguageLocaleKey = 'en_US'
            );
            insert adminUser;

            Config__c config = new Config__c(
                                      System_Admin_Id__c = user1.Id
            );
            insert config;

but turned out that the user.Profile.name is null. Please help me.

1 Answer 1

1

Try to use runas method in your test class

@isTest
private class TestRunAs {
public static testMethod void testRunAs() {
    // Setup test data
    // Create a unique UserName
    String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
    // This code runs as the system user
    Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
    User u = new User(Alias = 'standt', Email='[email protected]',
    EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
    LocaleSidKey='en_US', ProfileId = p.Id,
    TimeZoneSidKey='America/Los_Angeles',
     UserName=uniqueUserName);

    System.runAs(u) {
          // The following code runs as user 'u'
          System.debug('Current User: ' + UserInfo.getUserName());
          System.debug('Current Profile: ' + UserInfo.getProfileId());
      }
}}

Refer: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_runas.htm

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .