function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Big EarsBig Ears 

Apex test classes and Sharing rules - Question

Hey all,

I was hoping to get something confirmed. I'm stumped by an issue whereby sharing rules don't seem to be being implemented in a test class.
  • For Contacts, we have a criteria based sharing rule that shares Contacts with a particular group of users if the contact is a particular record type
  • The user group that is shared to is based upon roles within the hierarchy
  • I've written a test class that creates a Contact with the specified record type and runs as a user within the already mentioned group (they have the right role)
  • When running the test as the user, I realised that the user couldn't see the Contacts
  • After trouble-shooting, I queried for the ContactShare records of the Contact and found that the criteria based sharing hasn't been implemented when the Contact was created
Is this a commonly known behaviour?
- If so, that's frustrating as I need to run the test as the user in-order to test other behaviours. Is there a workaround?
- If not, then there may be a problem in my code and I'll double/triple/quadruple check my code to see why the shares aren't being implemented.

With thanks,
Andy
Best Answer chosen by Big Ears
Big EarsBig Ears
Sorry - I've just realised that Criteria Based Sharing rules aren't evaluated during Apex test classes - https://help.salesforce.com/HTViewHelpDoc?id=security_sharing_cbs_about.htm&language=en_US (https://help.salesforce.com/HTViewHelpDoc?id=security_sharing_cbs_about.htm&language=en_US)

The documentation states that "Criteria Based Sharing Rules cannot be tested" which I assume this refers to this.

Frustratingly, I'm now having issues with the manual sharing record I've created as a workaround in my test - That's not being recognised either...

All Answers

Big EarsBig Ears
Sorry - I've just realised that Criteria Based Sharing rules aren't evaluated during Apex test classes - https://help.salesforce.com/HTViewHelpDoc?id=security_sharing_cbs_about.htm&language=en_US (https://help.salesforce.com/HTViewHelpDoc?id=security_sharing_cbs_about.htm&language=en_US)

The documentation states that "Criteria Based Sharing Rules cannot be tested" which I assume this refers to this.

Frustratingly, I'm now having issues with the manual sharing record I've created as a workaround in my test - That's not being recognised either...
This was selected as the best answer
Jack D PondJack D Pond
This is a very ugly kludge workaround and if anyone knows a better way I'm all ears.

Problem: Test cases fail because "Criteria Based Sharing Rules cannot be tested" (records create 
Kludge:
  1. Create custom permission set in test class
  2. Apply it to created user
  3. Test away
Test class routine to set up a permission set (in test class, static for use with all tests, in this case for 'Account' and 'Contact' standard objects)
// Add PermissionSet 
    Static public PermissionSet SetupPermissionSet(){
        PermissionSet ps = new PermissionSet(Name='Slkjdjkl',Label='lksdjf');
        insert ps;
        List<ObjectPermissions> op = new List<ObjectPermissions>();
        op.add(new ObjectPermissions(ParentId=ps.Id,
                                     SobjectType='Account',
                                     PermissionsRead=true,
                                     PermissionsViewAllRecords=true));
        op.add(new ObjectPermissions(ParentId=ps.Id,
                                     SobjectType='Contact',
                                     PermissionsRead=true,
                                     PermissionsViewAllRecords=true));
        insert op;
        return ps;
    }
assign that Permission set to previously defined user (u):
insert new PermissionSetAssignment(PermissionSetId=SetupPermissionSet().Id AssigneeId=u.Id);
True, this does not test the sharing, but at least the test case won't fail from permissions error.


 
Kishor Ambekar 11Kishor Ambekar 11
Criteria based sharing will not be executed from test class, so we need to do below technique to share the records. In below example I am sharing a sample account with a usere using apex sharing in test class.

 @istest public class sampleTestClass {
   @isTest static void sampleTestMethod() {

        User testuser = TestDataFactory.getUser('ProfileName');

        Account Acc= new Account(Name='Test Account');
        insert Acc;

        //Apex sharing to share the Account with User
        AccountShare accShare= new AccountShare();
        accShare.AccountId = Acc.Id;
        accShare.AccountAccessLevel='Edit';
        accShare.OpportunityAccessLevel='Read';
        accShare.UserOrGroupId = testuser.Id;
        accShare.RowCause='manual';
        Database.SaveResult sr = Database.insert(accShare,false);
        if(sr.isSuccess()){
            system.debug('Record shared successfully!');
        }
        else {
            Database.Error err = sr.getErrors()[0];
            system.debug('Error message: '+err.getMessage());
        }
    }
}