0

I have an Apex Test where I have problems with my Permissions. But even with the right Permission Sets I can't insert Quotes.

Here's my code :

   Profile p = [SELECT Id FROM Profile WHERE Name='Custom User']; 
    User u = new User(Alias = 'standt', Email='standarduser@mail.com', 
          EmailEncodingKey='UTF-8', LastName='Testing', ProfileId = p.Id, UserName='standarduser@mail.com');
    insert u;
    System.runAs(u) {
            PermissionSet ps = [SELECT Id FROM PermissionSet WHERE Label = 'Salesforce CPQ User' LIMIT 1];
            insert new PermissionSetAssignment(AssigneeId = u.id, PermissionSetId = ps.Id);
            SBQQ__Quote__c principalQuote = new SBQQ__Quote__c();
            principalQuote.RecordTypeId = quoteRecordTypeIdsByDeveloperName.get('MyRecordType');
            principalQuote.SBQQ__Opportunity2__c = opportunity.Id;
            insert principalQuote;
    }

But it says that I don't have the right permission to insert principalQuote. I found a bypass but I don't understand why. If I do :

SBQQ__Quote__c principalQuote = new SBQQ__Quote__c();
principalQuote.RecordTypeId = quoteRecordTypeIdsByDeveloperName.get('MyRecordType');
insert principalQuote;
principalQuote.SBQQ__Opportunity2__c = opportunity.Id;
update principalQuote;

It works. So basically I'm not able to insert my data with fields. I have to update it afterward. Is it something common in Apex behaviour and Permission Sets ?

4
  • 1
    I never tried it, but does it work to set the PermissionSetAssignment in the runAs() block? I would usually expect users not to be able to give themselves permissions. – Florian Heer May 5 '20 at 10:23
  • @FlorianHeer It works thx, earlier I had a dml exception and I moved the runAs but in the wrong side ! – Jack May 5 '20 at 12:30
  • @FlorianHeer But why there's not an exception for that case ? Something like "You don't have the right to assign a permission set" – Jack May 5 '20 at 12:36
  • I would have expected some explicit error as well - sorry, I have no explanation :-) – Florian Heer May 5 '20 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.