+ Start a Discussion
TemesgenTemesgen 

Apex Test Class with profile

Hello everyone!
I am trying to reach 100% test coverage for the following code, currently it's 88%. I received this error: 

System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Cannot create a portal user without contact: [ContactId]

The profile is a community user profile, how can I solve this problem. Any help would be welcome, thank you.
 
public class StudentCheckController {
    public List<Class__c> classes{get; set;}
    String dayFormat = 'MM/DD';
    public Id classId{get; set;}
    public string userEmail{get;set;}
    public string userProfile;

    public StudentCheckController(ApexPages.StandardController sc) {
        userEmail = UserInfo.getUserEmail();
        userProfile = UserInfo.getProfileId();
        System.debug(userProfile);
        getClasses();

    }
    public void getClasses() {
        Id cohortRecordTypeId = Schema.SObjectType.class__c.getRecordTypeInfosByName().get('Cohort').getRecordTypeId();

        System.debug(cohortRecordTypeId);
        // Limit visibility to SSS community user
        if(userProfile != '00a7i000000dSK9OOL') {
            
            classes = [ SELECT
                id,
                name,
                class_nights__c,
                start_date__c,
                end_date__c,
                status__c,
                class__c,
                instructor__r.email
                FROM class__c WHERE RecordTypeId = :cohortRecordTypeId AND status__c = 'Active'];
                System.debug(classes);

        } else {
            classes = [ SELECT
                id,
                name,
                class_nights__c,
                start_date__c,
                end_date__c,
                status__c,
                class__c,
                instructor__r.email
                FROM class__c WHERE  RecordTypeId = :cohortRecordTypeId AND status__c = 'Active' AND instructor__r.email = :userEmail];
                System.debug(classes);

        }
    }

    public Pagereference newPage() {
        // Pagereference pf = new Pagereference('/apex/StudentList?id=' + classId);
        Pagereference pf = new Pagereference('https://armhat.force.com/coordinatorportal/StudentList?id=' + classId);
        return pf;
    }
}
 
Test Class:


@isTest
public class StudentCheckControllerTest {
   

static testMethod void testGetClassesNotEqualToProfile(){
        class__c newClass = new class__c(name = 'Test Class', class_nights__c = 'Monday / Wednesday', start_date__c = date.today() - 10, end_date__c = date.today() + 45);
        insert newClass;
        ApexPages.StandardController sc = new ApexPages.StandardController(newClass);
        StudentCheckController pc = new StudentCheckController(sc);
        pc.userEmail = 'test@gmail.com';
        pc.newPage();
        pc.userEmail = 'dreyes@armhat.com';
        pc.getClasses();
    }

static testMethod void testGetClassesEqualToProfile(){
        
        UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
        system.debug('portalRole is ' + portalRole);
        
        Profile p = [SELECT Id FROM Profile WHERE Id='00a7i000000dSK9OOL']; 

        User u = new User(Alias = 'testUser', UserRoleId = portalRole.Id, Email='standarduser@testorg.com', 
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = p.Id, 
        TimeZoneSidKey='America/New_York', UserName='testUser@example.com');
        

        System.runAs(u) {
        

class__c newClass = new class__c(name = 'Test Class', class_nights__c = 'Monday / Wednesday', start_date__c = date.today() - 10, end_date__c = date.today() + 45);
        insert newClass;
        ApexPages.StandardController sc = new ApexPages.StandardController(newClass);
        StudentCheckController pc = new StudentCheckController(sc);
        pc.userEmail = 'test@gmail.com';
        pc.newPage();
        pc.userEmail = 'dreyes@armhat.com';
        pc.getClasses();
    }

Best Answer chosen by Temesgen
Andrew GAndrew G
basically, as noted, you cannot create a community user without an associated Contact record. So create Account and Contact and associate the contact when creating the user record.  
Also, hard coded Ids are not best practice.
    Id p = [select id from profile where name='MyCommunity UserProfile'].id;
       
    Account ac = new Account(name ='Test') ;
    insert ac; 
     
    Contact con = new Contact(LastName ='testCon',AccountId = ac.Id);
    insert con;  
                  
    User user = new User(alias = 'test123', email='test123@noemail.com',
                emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
                localesidkey='en_US', profileid = p, country='United States',IsActive =true,
                ContactId = con.Id,
                timezonesidkey='America/Los_Angeles', username='tester@noemail.com');
       
    insert user;
    system.runAs(user) {
            // statements to be executed by this test user.
    }

regards
Andrew
 

All Answers

Andrew GAndrew G
basically, as noted, you cannot create a community user without an associated Contact record. So create Account and Contact and associate the contact when creating the user record.  
Also, hard coded Ids are not best practice.
    Id p = [select id from profile where name='MyCommunity UserProfile'].id;
       
    Account ac = new Account(name ='Test') ;
    insert ac; 
     
    Contact con = new Contact(LastName ='testCon',AccountId = ac.Id);
    insert con;  
                  
    User user = new User(alias = 'test123', email='test123@noemail.com',
                emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
                localesidkey='en_US', profileid = p, country='United States',IsActive =true,
                ContactId = con.Id,
                timezonesidkey='America/Los_Angeles', username='tester@noemail.com');
       
    insert user;
    system.runAs(user) {
            // statements to be executed by this test user.
    }

regards
Andrew
 
This was selected as the best answer
TemesgenTemesgen
I understand, thank you for your help Andrew!