1

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='[email protected]', 
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = p.Id, 
        TimeZoneSidKey='America/New_York', UserName='[email protected]',
        Profile.PermissionsApiUserOnly='true');

But, I get

Invalid field Initializer error on Profile.PermissionsApiUserOnly

Any help would be greatly appreciated. Thanks!

1 Answer 1

1

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

You must log in to answer this question.

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