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
                 name='Balamurugan Nadar'];
        Profile p = [select id 
                            name='BMCC system Admin SSO']; 

        User bdeUser = new user(alias = 'test123', email='[email protected]',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='[email protected]'); 
        insert bdeUser;

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

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

        Contact newContact = new Contact();
        newContact.LastName = 'testContactName';
        newContact.Email = '[email protected]';
        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;

        newOpp.Client_Interest__c = 'Phone Not Reachable';
        update newOpp;  

        Opportunity newOpp1 = [select id, client_interest__c, enquiry_for__c, Name, StageName, ownerId,MailSentNotContactable__c
                          Id =: newOpp.id];

        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 
                                           name = 'OPC' 
                                           sObjectType = 'Operation__c'];
        Profile p1 = [select id 
                            name='Force.com - One App User BCS']; 

        User opUser = new user(alias = 'test123', email='[email protected]',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='[email protected]', 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
                            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);
  • 1
    Do your test classes involve multiple users via System.runAs?
    – Keith C
    Commented Aug 20, 2014 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
    Commented Aug 20, 2014 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
    Commented Aug 20, 2014 at 7:43

2 Answers 2


As suggested in a comment:

PermissionSet ps = [SELECT Id 
                    FROM PermissionSet 
                    WHERE Name = '<required permission set name>'];
insert new PermissionSetAssignment(AssigneeId = opUser.Id, PermissionSetId = ps.Id);
  • 1
    To avoid DML exceptions in your unit tests, you will need to run this in a separate context from your main test code, wrapping either this or your test code in independent runAs() blocks.
    – Shanerk
    Commented Oct 20, 2020 at 18:14

In addition to @patlatus 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(new User(Id = UserInfo.getUserId())) {
  insert userWithCustomPermission;

  //    Given a mocked Permission Set
  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

You must log in to answer this question.

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