16

I have set OWD to private and create a permission set to give access to object. We have removed all the object settings access from the concerned profile. Previously with OWD set to private, profile based object access was there. Now all the test classes are getting failed. Error is coming in test classes that User must have Read Access to the record. So what should I do to assign permission set in test class so that my all test classes and its methods run perfectly.

Creation of Permission sets is necessary as same profile users do not have access to a object.

 static testMethod void myUnitTest16() {

    User u = [Select id
                 from
                 User
                 where
                 name='Balamurugan Nadar'];
    system.runAs(u){
        Profile p = [select id 
                            from 
                            Profile 
                            where 
                            name='BMCC system Admin SSO']; 

        User bdeUser = new user(alias = 'test123', email='test123@noemail.com',related_team__c = 'BDE', 
                            emailencodingkey='UTF-8', firstName='Nahush', lastname='Testing', languagelocalekey='en_US',
                            localesidkey='en_IN', profileid = p.Id, country='India',
                            timezonesidkey='Asia/Kolkata', username='test_g@noemail.com'); 
        insert bdeUser;


        RecordType rec = [Select Id, name , sObjectType
                                         From 
                                         RecordType 
                                         where 
                                         SObjectType = 'Opportunity'
                                         AND
                                         name ='OPC'];                                                 

        Account newAccount = new Account();
        newAccount.Name = 'testAccount';
        insert newAccount;

        Contact newContact = new Contact();
        newContact.LastName = 'testContactName';
        newContact.Email = 'rohit.k@bmcgroup.in';
        newContact.AccountId = newAccount.id;
        insert newContact;


        Opportunity newOpp = new Opportunity();
        newOpp.Name = 'testOpp16';
        newOpp.AccountId = newAccount.id;
        newOpp.Contact__c = newContact.id;
        newOpp.StageName = 'Negotiation';
        newOpp.CloseDate = system.today();
        newOpp.underTest__c = TRUE;
        newOpp.Enquiry_For__c = 'One Person Company Registration';
        newOpp.Converted_to_operation__c = false;
        newOpp.Ownerid = bdeUser.id;
        insert newOpp;

        test.startTest();
        newOpp.Client_Interest__c = 'Phone Not Reachable';
        update newOpp;  

        Opportunity newOpp1 = [select id, client_interest__c, enquiry_for__c, Name, StageName, ownerId,MailSentNotContactable__c
                          from 
                          Opportunity
                          Where
                          Id =: newOpp.id];
        system.debug('-MailSentNotContactable__c-'+newOpp1.MailSentNotContactable__c);                  

        OpportunityContactRole newOppContactRole = new OpportunityContactRole();
        newOppContactRole.ContactId = newContact.id;
        newOppContactRole.OpportunityId = newOpp.id;
        newOppContactRole.IsPrimary = true;
        insert newOppContactRole;

        newOpp.Amount = 12000;
        newOpp.CloseDate = system.today();
        newOpp.Enquiry_For__c = 'One Person Company Registration';
        newOpp.underTest__c = TRUE;
        newOpp.Converted_to_operation__c = false;
        newOpp.BDE_Description__c ='Test';
        newOpp.Number_of_Partner__c= 3;
        newOpp.ROC_Name__c= 'Goa--Goa Daman and Diu';
        newOpp.DSC_Application__c= 'With Token';
        newOpp.StageName = 'Closed Won';
        newOpp.Document_received__c = 'Complete Document Received';
        newOpp.Mode_of_Payment__c = 'Cheque';
        newOpp.Amount_Receivd__c= 15000;
        newOpp.Auth_Capital__c = 100000;
        newOpp.Paid_Up_Capital__c =100000;
        newOpp.Client_Nature__c = 'Aggresive';
        newOpp.First_Installment_Received__c = true;
        newOpp.Payment_Receipt_Uploaded__c = true;


        update newOpp;

        RecordType recOp = [select id, name, SObjectType 
                                           from 
                                           RecordType 
                                           where 
                                           name = 'OPC' 
                                           and 
                                           sObjectType = 'Operation__c'];
        Profile p1 = [select id 
                            from 
                            Profile 
                            where 
                            name='Force.com - One App User BCS']; 

        User opUser = new user(alias = 'test123', email='test123@noemail.com',related_team__c = 'Operation', related_bde__c = 'Rohit Akojwar',
                            emailencodingkey='UTF-8', firstName='Pawan', lastname='Testing', languagelocalekey='en_US',
                            localesidkey='en_US', profileid = p1.Id, country='United States',
                            timezonesidkey='America/Los_Angeles', username='test01@noemail.com', service_segment__c='Company Registration'); 
        insert opUser;

        Operation__c testOp = [Select id, enquiry_For__c, account__c, contact__c, Opportunity__c, service_segment__c
                            from Operation__c
                            where
                            Opportunity__c =: newOpp.id];


        testOp.Initial_mail_sent__c = true;
        testOp.RecordTypeId = recOp.id ;
        testOp.ownerId = opUser.id;
        testOp.Contact__c = newContact.id;
        testOp.Account__c = newAccount.id;
        testOp.service_segment__c = 'OPC Registration';

        update testOp;

        system.assertEquals( true, testOp.Initial_mail_sent__c);
        test.stopTest();
    } 
}
  • 1
    Do your test classes involve multiple users via System.runAs? – Keith C Aug 20 '14 at 7:22
  • I am using System admin as RunAs() and inserting user, similar to actual settings present in our org, in test class. I have added a test method. – Rohit Aug 20 '14 at 7:33
  • 5
    The last comment in this thread indicates that it is now possible to insert PermissionSetAssignment objects that relate a User and PermissionSet. So I suggest adding those inserts to your tests. – Keith C Aug 20 '14 at 7:43
16

This question is marked as unanswered, despite it was answered in the comments.

Let's revise the answer here:

PermissionSet ps = [SELECT Id FROM PermissionSet WHERE Name = '<required permission set name'];
insert new PermissionSetAssignment(AssigneeId = opUser.id, PermissionSetId = ps.Id);
0

In addition to @patiatus answer....

Should you need to setup a custom permission without needing to care about what permission set it belongs to ....

//  Given user
User userWithCustomPermission = new User (
    ... // setup fields for mocked User
};
System.runAs([SELECT Id FROM User WHERE Id = :UserInfo.getUserId()][0]) {
  insert userWithCustomPermission;

  //    Given user w/permissions
  PermissionSet ps = new PermissionSet(Label = 'mockPs', Name = 'mockPs');
  insert ps;

  // Given custom permission associated to the mocked PermissionSet
  SetupEntityAccess sea = new SetupEntityAccess(
            ParentId = ps.Id,
            SetupEntityId = [SELECT Id FROM CustomPermission
            WHERE DeveloperName = 'yourCustomPermissionApiName'][0].Id
    );
  insert sea;

  // Given mocked Permission Set assigned to user for test
  PermissionSetAssignment psa = new PermissionSetAssignment(
            AssigneeId = userWithCustomPermission,
            PermissionSetId = ps.Id
  );
  insert psa;
}

...
// When code under test invoked ...
System.runAs(userWithCustomPermission) {
  new MyCode().doSomething();
}

// Then verify 
... asserts
  • Two notes: 1) No need on for the User Query, System.runAs(new User(Id = UserInfo.getUserId()){ } will do fine. 2) Might be considered offtopic since OP asked about Permission Sets and your code deals with Custom Permissions – Christian Szandor Knapp Mar 13 at 22:59
  • @ChristianSzandorKnapp - re: #1 -- of course! -- I'm an idiot - I never thought of that; #2 - you are right as well - I amended the text to help keep it off the "off topic" purge list – cropredy Mar 14 at 0:08

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.