+ Start a Discussion

INVALID_CROSS_REFERENCE_KEY when insert Customer Portal User

Hi there,


I'm trying to create test coverage for a trigger over User object, soI need to create a User to fire the trigger. I coded a test class following this: http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_dml_non_mix_sobjects.htm?SearchType


This is how it looks like:


public class UserTriggerHandlerTest {
        @isTest (seeAllData=true)
        static void testUserCreate(){
                // Setup test data
                // This code runs as the system user
                Profile p = [SELECT Id
                             FROM Profile
                             WHERE Name='Portal User'];
                Profile p2 = [SELECT Id
                              FROM Profile
                              WHERE Name='System Administrator'];
                User u = new User(Alias = 'custPort', Email='customer@portal.com',
                EmailEncodingKey='UTF-8', LastName='Portal', LanguageLocaleKey='en_US',
                LocaleSidKey='en_US', ProfileId = p.Id,
                TimeZoneSidKey='America/Los_Angeles', UserName='customer@portal.com');
                User u2 = new User(Alias = 'admn', Email='admin@test.com',
                EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
                LocaleSidKey='en_US', ProfileId = p2.Id,
                TimeZoneSidKey='America/Los_Angeles', UserName='customer@portal.com');
                System.runAs(u2) {
                        insert u;


The test fails with the following message:

FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
FATAL_ERROR Class.UserTriggerHandlerTest.testUserCreate: line 23, column 1


Any ideas? Does anyone know how to avoid this or any workaround to do test coverage for a trigger over User?






with out inserting u2, you are using that user as running user, Insert u2 before u do 

System.runAs(u2) {

Actually you don't have to insert it, according to the documentation I provided.

I believe system.runas(u2) "fakes" the creation of that user for the tests.


yes, they inserted the user before they used it in system.runas api.


private class MixedDML {
static testMethod void MixedDMLExample() {
User u;
Account a;
User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
// Insert account as current user
System.runAs (thisUser) {
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name='SalesRep'];
u = new User(alias = 'jsmtih', email='jsmith@acme.com',
emailencodingkey='UTF-8', lastname='Smith',
localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
insert u;
a = new Account(name='Acme');
insert a;
// Update account as the new user
System.runAs(u) {
a.website = 'www.salesforce.com';
update a;