I'm writing a test class for some trigger functionality and I keep getting the below error when attempting to insert a Case as a User with a specific Profile/Role/Department.
INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: a0QXXXXXXXXXXXX
The error references a Custom Object that I'm trying to associate to a Case via Lookup.
The Custom Object has OWD as inherited from it's Parent which is Contact which is itself has OWD inherited from it's Parent which is Account. Account is set to Private with Sharing rules. All Accounts are owned by a single designated User record.
Below is my code.
UserRole theRole = [SELECT Id FROM UserRole WHERE Name = :Constants.ROLE];
Profile theProfile = [SELECT Id FROM Profile WHERE Name = 'Department'];
User theUser = TestingUtils.createTestUser(theRole.Id, theProfile.Id, 'CST', 'User');
theUser.Department = 'CST';
System.runAs( new User(Id = UserInfo.getUserId()) )
{
insert theUser;
}
System.debug( theUser.Name );
Account acc = new Account
(
RecordTypeId = DatabaseUtils.getRecordTypeId('Account', Constants.PERSON_ACCOUNT),
FirstName = 'FirstT2',
LastName = 'LastT2',
PersonEmail = '[email protected]'
);
insert acc;
Contact person = [SELECT Id FROM Contact WHERE AccountId = :acc.Id];
Custom_Object__c custom = new Custom_Object__c
(
RecordTypeId = DatabaseUtils.getRecordTypeId('Custom_Object__c',Constants.RETAIL_ACCOUNT),
Account_Owner__c = person.Id,
CustomerAccountNumber__c = 'TestAccountNum',
Name = 'testname',
AccountNumber__c = 'AccountNum'
);
insert custom;
Custom_Object__c testCustom = [SELECT Id FROM Custom_Object__c WHERE Id = :custom.Id LIMIT 1];
System.runAs(theUser)
{
Case testCase = new Case
(
RecordTypeId = DatabaseUtils.getRecordTypeId('Case', 'Phone'),
Custom_Object__c= testCustom.Id,
Status = 'New',
Origin = 'Inbound Phone',
Subject = 'Test',
Description = 'More Test',
);
Test.startTest();
insert testCase;
Test.stopTest();
}
I know this has something to do with Sharing because of I move the line Custom_Object__c testCustom = [SELECT Id FROM Custom_Object__c WHERE Id = :custom.Id LIMIT 1];
down to be in the System.runAs
the object does not get returned but for the life of me I can't figure out why the User doesn't have access to my Custom Object.
If I go through the UI the user has no problem accessing my Custom Object or associating it to a Case record.
EDIT: I can somewhat get around this if I set the OwnerId and CreatedById as the User in question and insert it as system user, and then update it as the User in question. This allows me proper testing when a Case is updated, but it doesn't allow me to test for Case creation.