0

I have somecustom objecy with a lookup users and want to give this users some permissions. I read and tried this https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_bulk_sharing_creating_with_apex.htm but is didn't work. Test failed and i dont understand part with "Creating Apex Managed Sharing"

For example i have object Test with lookup user field Manager and that user must have read-write access

test class doent work on line : System.assertEquals(JobSharing.manualShareRead(j.Id, user2Id), true);

UPD: Trigger works now, but test still failed.

    public class JobSharing {   
   public static boolean manualShareRead(Id recordId, Id userOrGroupId){
      
      Job__Share jobShr  = new Job__Share();   
     
      jobShr.ParentId = recordId;     
      jobShr.UserOrGroupId = userOrGroupId;       
    
      jobShr.AccessLevel = 'Read';
        
     
      jobShr.RowCause = Schema.Job__Share.RowCause.Manual;
      
      Database.SaveResult sr = Database.insert(jobShr,false);
     
      if(sr.isSuccess()){
        
         return true;
      }
      else {        
         if(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION  &&  
                  err.getMessage().contains('AccessLevel')){
           
            return true;
         }
         else{
            
            return false;
         }
       }
   }
   
}

    @isTest
private class JobSharingTest {
  
   static testMethod void testManualShareRead(){
     
      List<User> users = [SELECT Id FROM User WHERE IsActive = true LIMIT 2];
      Id User1Id = users[0].Id;
      Id User2Id = users[1].Id;
   
 
      Job__c j = new Job__c();
      j.Name = 'Test Job';
      j.OwnerId = user1Id;
      insert j;    
                 
      System.assertEquals(JobSharing.manualShareRead(j.Id, user2Id), true);
   
   
      List<Job__Share> jShrs = [SELECT Id, UserOrGroupId, AccessLevel, 
         RowCause FROM job__share WHERE ParentId = :j.Id AND UserOrGroupId= :user2Id];
      

      System.assertEquals(jShrs.size(), 1, 'Set the object\'s sharing model to Private.');
      
    
      System.assertEquals(jShrs[0].AccessLevel, 'Read');
      System.assertEquals(jShrs[0].RowCause, 'Manual');
      System.assertEquals(jShrs[0].UserOrGroupId, user2Id);
      
     
      delete j;   
   
      System.assertEquals(JobSharing.manualShareRead(j.Id, user2Id), false);
   }  
}

Trigger

trigger JobApexSharing on Job__c (after insert) {

if(trigger.isInsert){
    // Create a new list of sharing objects for Job
    List<Job__Share> jobShrs  = new List<Job__Share>();
    
    // Declare variables for recruiting and hiring manager sharing
    Job__Share recruiterShr;
    Job__Share hmShr;
    
    for(Job__c job : trigger.new){
        // Instantiate the sharing objects
        recruiterShr = new Job__Share();
        hmShr = new Job__Share();
        
        // Set the ID of record being shared
        recruiterShr.ParentId = job.Id;
        hmShr.ParentId = job.Id;
        
        // Set the ID of user or group being granted access
        recruiterShr.UserOrGroupId = job.Recruiter__c;
        hmShr.UserOrGroupId = job.Hiring_Manager__c;
        
        // Set the access level
        recruiterShr.AccessLevel = 'edit';
        hmShr.AccessLevel = 'read';
        
        // Set the Apex sharing reason for hiring manager and recruiter
        recruiterShr.RowCause = Schema.Job__Share.RowCause.Recruiter__c;
        hmShr.RowCause = Schema.Job__Share.RowCause.Hiring_Manager__c;
        
        // Add objects to list for insert
        jobShrs.add(recruiterShr);
        jobShrs.add(hmShr);
    }       
   
    Database.SaveResult[] lsr = Database.insert(jobShrs,false);        
    
    Integer i=0;
    
   
    for(Database.SaveResult sr : lsr){
        if(!sr.isSuccess()){                
            Database.Error err = sr.getErrors()[0];
            
            
            if(!(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION  
                                           &&  err.getMessage().contains('AccessLevel'))){
               
                trigger.newMap.get(jobShrs[i].ParentId).
                  addError(
                   'Unable to grant sharing access due to following exception: '
                   + err.getMessage());
            }
        }
        i++;
    }   
}
    
   }
5
  • Could you describe what did you try to do? What is failing? Which part you do not undestand? You need to go to classic, add a new sharing reason for you custom object there, and later on basically copy paste example from the documentation you've provided. May 3, 2021 at 11:18
  • @user1974566 i want to give lookup user acces to records. I created sharing reasons a few miutes ago, but it still didn't work even with Job object like in tutorial and test class doent work on line : System.assertEquals(JobSharing.manualShareRead(j.Id, user2Id), true);
    – Samuel143
    May 3, 2021 at 11:21
  • Please share your code May 3, 2021 at 11:22
  • @user1974566 edited., but now its like link code in my question.
    – Samuel143
    May 3, 2021 at 11:29
  • @user1974566 well, it works after logout and login to org, but test still failed.
    – Samuel143
    May 3, 2021 at 11:37

1 Answer 1

0

Couple of things here. First of all: Class connected to manual sharing and trigger for apex managed sharing are connected to two different things. Manual sharing is not persisting. That means it would be removed (manual sharing added to the user) on owner change for example. Sharing recalculations would be triggered and all of the manual sharing are removed at that moment. To overcome such an issue Apex Managed Sharing is used. Using it like in example from documentation would ensure persisting sharing even on the ownership change.

Your issue about the test class can be connected to couple of things and you need to look into logs to know what exactly is not working. I've recreated example from the docs and without additional customizations there are two issues which are easy to have: First of all when Job object is created, it probably have Public sharing set. Running test method would result in internal error connected to that. Second of all test is fetching two totally random users, which would not have correct licence for example.

You must log in to answer this question.

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