[SalesForce] Setting profile information for test user in apex test class

I'm creating a test method where I have to create a test user. I will be using runAs for this. But, in creating the actual test user, I'm unsure how to set profile items such as PermissionsApiUserOnly. Here is my code so far (taken from documentation):

    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/New_York', UserName='standarduser@testorg.com',
        Profile.PermissionsApiUserOnly='true');

But, I get

Invalid field Initializer error on Profile.PermissionsApiUserOnly

Any help would be greatly appreciated. Thanks!

Best Answer

You need to actually find a Profile that has that permission enabled. You cannot modify Profile permissions in your tests.

One alternative solution if you do not have any Profile set up with that permission (or simply wish to use another) is to create a Permission Set. Then you could create a PermissionSetAssignment for the User in question.

PermissionSet p = [SELECT Id FROM PermissionSet WHERE DeveloperName = 'API_Only'];
insert new PermissionSetAssignment(AssigneeId=u.Id, PermissionSetId = p.id);
Related Topic