How can I assign a permission set to a user in a test context?

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();
    } 
}

Answer

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);

Attribution
Source : Link , Question Author : Rohit , Answer Author : Community

Leave a Comment