7

I have a test class, with this code

System.debug(UserInfo.getProfileId());

Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User'];
User u = new User(ProfileId = p.Id, ...);
System.runAs(u)
{
    System.debug(UserInfo.getProfileId());

    Database.delete(records, false);
}

In the trigger handler that fires for this DML operation, when I output the current user`s Id

System.debug(UserInfo.getProfileId());

It does not get the Profile Id of the User that I set in the System.runAs method. It gets the Profile Id of the User... me, ie. the System Administrator, when it should be the Standard User.

Why?... And how to fix?

1

2 Answers 2

4

I have set up an MVR in my org (cs19). I ran the below code using API Version 37.0 and 39.0, both of which passed. So this behavior is not generally reproducible. You might share your API Version and instance name as well.

Test Class

@IsTest
class DemoTests
{
    static testMethod void testRunAsProfile()
    {
        final String PROFILE_NAME = 'Some Profile';
        User u = [
            SELECT Id FROM User WHERE IsActive = true
            AND Profile.Name = :PROFILE_NAME LIMIT 1
        ];
        system.runAs(u)
        {
            Profile p = [SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId()];
            system.assertEquals(PROFILE_NAME, p.Name);
            insert new MyObject__c();
        }
    }
}

Trigger

trigger MyObject on MyObject__c (before insert)
{
    final String PROFILE_NAME = 'Some Profile';
    Profile p = [SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId()];
    system.assertEquals(PROFILE_NAME, p.Name);
}
0

You may have to insert the user.

After you do:

User u = new User(ProfileId = p.Id, ...);

Do

insert u

I'm not sure that salesforce will actually recognise the user as vaild (ie: you may not be able to use System.runAs()) until it's been inserted.

Even @Adrian Larson's excellent example above uses an already existing user instead of creating and inserting it.

1
  • 1
    @mkmorman - RunAs DOES work as a user that has not been inserted. What I DO NOT know is if the userInfo will work properly if the user is not inserted. Maybe I will take AL's example and run the test later
    – Eric
    Feb 26, 2017 at 16:06

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.