[SalesForce] Error while running a test class to add a partner to a user group

This is the test class I have Written and every time I run the test I get the following error:

Class               addPartnerUsersToGroupTest
Method Name         TestaddPartnerUsersToGroup
Pass/Fail           Fail
Error Message       System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Cannot create a portal user without contact: [ContactId]
Stack Trace         Class.addPartnerUsersToGroupTest.TestaddPartnerUsersToGroup: line 26, column 1

For the test class beneath

@isTest (SeeAllData=true)
private class addPartnerUsersToGroupTest{
    public static Account partnerAccount; 
    static testMethod void TestaddPartnerUsersToGroup() {
        partnerAccount = new Account(Name = 'Test Partner Acccount');                                                                           
        insert partnerAccount; 
        Contact partnerContact = new Contact(FirstName = 'Test Contact',LastName = 'Test Contact',
                AccountId = partnerAccount.Id,Email = 'testemail'+Math.round(Math.random()*Math.pow(10, 7))+'@testemail.com');

         String communityNick = Math.round(Math.random()*Math.pow(10, 7))+'';
         Profile p = [Select p.Name, p.Id From Profile p where p.Name =: LABEL.Partner_Distributor];
           // Create Partner Users
         User partnerUser1 = new User();
         partnerUser1.LastName ='Test name';
         partnerUser1.Alias ='tetest';
         partnerUser1.Email ='testemail'+Math.round(Math.random()*Math.pow(10, 7))+'@testemail.com';
         partnerUser1.Username ='testemail'+Math.round(Math.random()*Math.pow(10, 7))+'@testemai.com';
         partnerUser1.CommunityNickname = 'TestCommunityName1'+communityNick.substring(0,4);
         partnerUser1.ProfileId = p.Id;
         partnerUser1.ContactId = partnerContact.Id;
         partnerUser1.TimeZoneSidKey ='Asia/Kolkata';
         partnerUser1.LocaleSidKey ='en_IN';
         partnerUser1.EmailEncodingKey ='UTF-8';
         partnerUser1.LanguageLocaleKey ='en_US';
         partnerUser1.isActive = true;
         insert partnerUser1;
    }    
}

Best Answer

According to the code, looks like you're referencing the contact ID of the contact record which is never inserted. Therefore the ID of the record will be null.

Make sure you insert the contact record after this line:

Contact partnerContact = new Contact(FirstName = 'Test Contact',LastName = 'Test Contact', AccountId = partnerAccount.Id,Email = 'testemail'+Math.round(Math.random()*Math.pow(10, 7))+'@testemail.com');
//missing
insert partnerContact;

so that you can reference the ID later on this line:

partnerUser1.ContactId = partnerContact.Id;