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
Daniel SassoneDaniel Sassone 

Assign value to ProfileId?

Hello!  I'm very new to Apex and programming in general.

 

I'm creating a test class, but every time I run the test I get an error with my ProfileID.  I tried just taking it out, but it's a required field.  I tried assigning a random value to it directly (ie: u.ProfileID = '00Ee0000000CodE';)  but that gives me an error that the ID is invalid.  So I'm assuming I need to reference the ID.  I have no idea how to do that however, so any help would be greatly appreciated!

 

Here is my code.

@isTest
private class UserContactTest {
    testmethod static void userCreationTest(){
        User u = new User();
        u.Firstname = 'mike';
        u.LastName = 'Smith';
        u.email = 'msmith@company.com';
        u.Alias = 'alias';
        u.CommunityNickname = 'commnick';
        u.EmailEncodingKey = 'UTF-8';
        u.Username = 'msmith@company.com';
        u.TimeZoneSidKey = 'America/Denver';
        u.LocaleSidKey = 'en_US';
        u.EmailEncodingKey = 'UTF-8';
        u.LanguageLocaleKey = 'en_US';
        //u.ProfileId = [SELECT id FROM ]; //not really sure what I'm doing here
        insert u;
    }
}

 

John Pipkin 14John Pipkin 14
Daniel, 

Try this:
u.ProfileId = [Select Id from Profile where Name = 'System Administrator'].Id;

Hope that helps!
Prem Anandh 1Prem Anandh 1
Hi Daniel, 

Are you creating user for Saleforce Internal or Community user?

If it's for Internal Salesforce User then CommunityNickname is not required.

Hope below code will help you.
 
@isTest
private class UserContactTest {
    testmethod static void userCreationTest(){
        User u = new User();
        u.Firstname = 'mike';
        u.LastName = 'Smith';
        u.email = 'msmith@company.com';
        u.Alias = 'alias';
        u.EmailEncodingKey = 'UTF-8';
        u.Username = 'msmith@company.com';
        u.TimeZoneSidKey = 'America/Denver';
        u.LocaleSidKey = 'en_US';
        u.EmailEncodingKey = 'UTF-8';
        u.LanguageLocaleKey = 'en_US';
        u.ProfileId = [Select Id from Profile where Name = 'System Administrator'].Id;
        insert u;
    }
}


Thanks,
Prem Anandh
Daniel SassoneDaniel Sassone

John,

I've run into another error, but your suggested code worked perfectly!  Thank you!