Loading

UserInfo.getProfileId() returns invalid profileId in apex test class

Fecha de publicación: Aug 21, 2024
Descripción
If we have an apex test class which queries on Profile object under the Automated Process user context the query fails and doesn't return any records starting api version 41.0. Please note this behavior is noticed only if we use UserInfo.getProfileId() as SOQL filter condition.

This is because starting api version 41.0 there are 2 internal users which are exposed in test class context. These users does not have normal profiles which is resulting in the error. 
Solución
This behavior is Working As Designed.

With the introduction of API v41.0, 2 internal users were added to the system "Automated Process" and "Data.com Clean". They are non standard users who do not have normal profiles used for internal operations. With advancing the API, these users are available in test class context and are being loaded instead of the user that is being loaded with API v40 or lower. This is resulting in the error.

As a workaround, create a test user in the apex test class context and perform the logic under that user using System.runAs(testUsr) instead of query the user or profile with UserInfo.getProfileId() method. Below are apex test class code samples for Working & Non-Working scenario.

 Non Working Scenario:
 
@isTest(SeeAllData = false)
private class ProfileCheckTest {
    static testMethod void testStartDate() {
        User usr = [SELECT Id FROM User WHERE Name ='Automated Process' limit 1];
        System.runAs(usr) {
            String profileName = [SELECT Name FROM Profile WHERE Id =: UserInfo.getProfileId() LIMIT 1].Name;
        }
    }
}

 Working Scenario:
 
@isTest(SeeAllData = false)
private class ProfileCheckTest {
    static testMethod void testStartDate() {
        User usr = new User();
        usr.ProfileId = [SELECT Id FROM Profile WHERE Name != 'System Administrator' limit 1].Id;                   
        usr.LastName = 'Test';
        usr.Email = 'test@test.com';
        usr.Username = 'test@test.com' + System.currentTimeMillis();
        usr.CompanyName = 'Salesforce';
        usr.Title = 'Title';
        usr.Alias = 'Roger';
        usr.TimeZoneSidKey = 'America/Los_Angeles';
        usr.EmailEncodingKey = 'UTF-8';
        usr.LanguageLocaleKey = 'en_US';
        usr.LocaleSidKey = 'en_US';

        System.runAs(usr) {
            String profileName = [SELECT Name FROM Profile WHERE Id =: UserInfo.getProfileId() LIMIT 1].Name;
        }
    }
}

NOTE: The code provided is an example. You'll need to review and make modifications for your organization.
Número del artículo de conocimiento

000383816

 
Cargando
Salesforce Help | Article