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',

But, I get

Invalid field Initializer error on Profile.PermissionsApiUserOnly

Any help would be greatly appreciated. Thanks!


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);
| improve this answer | |
  • Also, there is no need to put quotes around true, since it is not a string, but a boolean. – Sebastian Kessel May 18 '16 at 15:26
  • 1
    @SebastianKessel Good eye. I didn't even notice b/c I was wrapped up in the strategy itself. – Adrian Larson May 18 '16 at 15:36
  • Looks like DeveloperName for PermissionSet is out of date now - you can use 'Name' instead. – Aislinn Hayes Jan 20 '17 at 15:54

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.