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
test vijaytest vijay 

How to create AccountShare in apex Testclass

hy Guys,
I want to Create  AccountSahre WHERE RowCause='Territory'  such as I created AccountShare object I got this error : Error message: field integrity exception: RowCause (cannot insert sharing row with this cause).
following is piece of code of  my apex class and I am sure if i got accountShare object in test class then my requirment will be fulfuill.
Map<Id,account> accountMap = new Map<Id,account>();
set<Id> setAccShareIds = new set<Id>();
 for (Account a : [SELECT Id,Name, (SELECT UserOrGroupId from Shares WHERE RowCause='Territory') 
                   FROM Account WHERE Id IN :accountIds]) {
            accountMap.put(a.Id,a);
            if(!a.Shares.isEmpty()) {
                for(AccountShare s : a.Shares) {
                    setAccShareIds.add(s.UserOrGroupId);
                }
            }
        }
I have tried many way but not successed. can anybody know me how to resolve this issue.
Thanks In Advance
 
Best Answer chosen by test vijay
ravi soniravi soni
Hy Vijay,
I have faced this error  Error message: field integrity exception: RowCause (cannot insert sharing row with this cause).
I think when you was trying to create accountShare object in testClass at that time  you got this error  but I think you don't need to create accountShare object in test class.
follow follwoing steps to create accountShare and any share object in apex.

if you want accountShare object and any share object with  RowCause 'Territory' in your apexTest class then you must follow following steps.
1. In your org, search Territory in the quick find box and select Territory Models.
2. click View Rules which  state is "active".

Note - if you not found Territory Models then you have to follow following referance url.
How to enabled Territory for salesforce.
 Follow - https://trailhead.salesforce.com/content/learn/modules/territory-management-basics
 
3. open any rule.
4. In Rule Criteria Section check at which filed rule is apply.
For instance :  Account: Industry EQUALS Apparel    
 above rule means you will have to set account industry with Apparel value in your test class while inserting Account Object.
 you will have to set that value  in test class account field.

get reference from following Class.
//Main Class
public class accountShareApex {
    public static void test_unit(set<Id> accountIds){
        
    Map<Id,account> accountMap = new Map<Id,account>();
set<Id> setAccShareIds = new set<Id>();
 for (Account a : [SELECT Id,Name, (SELECT UserOrGroupId from Shares WHERE RowCause='Territory') 
                   FROM Account WHERE Id IN :accountIds]) {
            accountMap.put(a.Id,a);
            if(!a.Shares.isEmpty()) {
                for(AccountShare s : a.Shares) {
                    setAccShareIds.add(s.UserOrGroupId);
                }
            }
        }

}
}
 
//Test Class
@isTest
public class accountShareApexTest {
@isTest
    public static void testExcute(){
        set<Id> accountId = new set<Id>();
     Profile pf= [Select Id from profile where Name='System Administrator' limit 1]; 
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        
        User uu=new User(firstname = 'ABC', 
                         lastName = 'XYZ', 
                         email = uniqueName + '@test' + orgId + '.org', 
                         Username = uniqueName + '@test' + orgId + '.org', 
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id,
                         isActive = True
                        ); 
                        
          insert uu;
        
        
        
        Account aAccount = new Account();
        aAccount.Phone = '444555';
        aAccount.Name = 'test';
        aAccount.Type = 'Prospect';
        aAccount.Industry = 'Technology';    
        aAccount.ownerId = uu.Id;
        insert aAccount;
        accountId.add(aAccount.Id);
        
         
           List<AccountShare> lstAccountShare = [SELECT Id, AccountId, RowCause FROM AccountShare 
                                                 Where RowCause = 'Territory' limit 1];
        system.debug('lstAccountShare===> ' + lstAccountShare);
        accountShareApex.test_unit(accountId);
        
      
      }
}
Remember that your rules alwas asign with Territory and if multi rules are assigned and active, you must add all active condition.

In my org, Rule Criteria
1. Account: IndustryEQUALSTechnology
2. Account: TypeEQUALSProspect

both rules are active.
let me know if it helps you and marking it as best answer so that it can help to others in future.
Thank You
 



 

All Answers

ravi soniravi soni
Hy Vijay,
I have faced this error  Error message: field integrity exception: RowCause (cannot insert sharing row with this cause).
I think when you was trying to create accountShare object in testClass at that time  you got this error  but I think you don't need to create accountShare object in test class.
follow follwoing steps to create accountShare and any share object in apex.

if you want accountShare object and any share object with  RowCause 'Territory' in your apexTest class then you must follow following steps.
1. In your org, search Territory in the quick find box and select Territory Models.
2. click View Rules which  state is "active".

Note - if you not found Territory Models then you have to follow following referance url.
How to enabled Territory for salesforce.
 Follow - https://trailhead.salesforce.com/content/learn/modules/territory-management-basics
 
3. open any rule.
4. In Rule Criteria Section check at which filed rule is apply.
For instance :  Account: Industry EQUALS Apparel    
 above rule means you will have to set account industry with Apparel value in your test class while inserting Account Object.
 you will have to set that value  in test class account field.

get reference from following Class.
//Main Class
public class accountShareApex {
    public static void test_unit(set<Id> accountIds){
        
    Map<Id,account> accountMap = new Map<Id,account>();
set<Id> setAccShareIds = new set<Id>();
 for (Account a : [SELECT Id,Name, (SELECT UserOrGroupId from Shares WHERE RowCause='Territory') 
                   FROM Account WHERE Id IN :accountIds]) {
            accountMap.put(a.Id,a);
            if(!a.Shares.isEmpty()) {
                for(AccountShare s : a.Shares) {
                    setAccShareIds.add(s.UserOrGroupId);
                }
            }
        }

}
}
 
//Test Class
@isTest
public class accountShareApexTest {
@isTest
    public static void testExcute(){
        set<Id> accountId = new set<Id>();
     Profile pf= [Select Id from profile where Name='System Administrator' limit 1]; 
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        
        User uu=new User(firstname = 'ABC', 
                         lastName = 'XYZ', 
                         email = uniqueName + '@test' + orgId + '.org', 
                         Username = uniqueName + '@test' + orgId + '.org', 
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id,
                         isActive = True
                        ); 
                        
          insert uu;
        
        
        
        Account aAccount = new Account();
        aAccount.Phone = '444555';
        aAccount.Name = 'test';
        aAccount.Type = 'Prospect';
        aAccount.Industry = 'Technology';    
        aAccount.ownerId = uu.Id;
        insert aAccount;
        accountId.add(aAccount.Id);
        
         
           List<AccountShare> lstAccountShare = [SELECT Id, AccountId, RowCause FROM AccountShare 
                                                 Where RowCause = 'Territory' limit 1];
        system.debug('lstAccountShare===> ' + lstAccountShare);
        accountShareApex.test_unit(accountId);
        
      
      }
}
Remember that your rules alwas asign with Territory and if multi rules are assigned and active, you must add all active condition.

In my org, Rule Criteria
1. Account: IndustryEQUALSTechnology
2. Account: TypeEQUALSProspect

both rules are active.
let me know if it helps you and marking it as best answer so that it can help to others in future.
Thank You
 



 
This was selected as the best answer
test vijaytest vijay
hy veer,
Thanks, it's working.