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
_why the unlucky stiff_why the unlucky stiff 

Building a set of Users in a Test Class

Hello Folks, I need a set of users under different profiles to build data for my test case. What is the best way to go about this? If I try to build this Manually, I face a series problems, i.e DML will fail saying OwnerId is missing etc. Can anybody guide me the best way to do this?

list<User> lUsr = new list<User>();
        
        User oUsr = new User();
        oUsr.FirstName = 'James';
        oUsr.LastName = 'Dean';
        oUsr.Email = 'james@dean.com';
        oUsr.Username = 'jdean@jamesdean.com';
        oUsr.Alias = 'jdean';
        oUsr.CommunityNickname = 'j1234';
        OUsr.TimeZoneSidKey = 'America/Denver';
        oUsr.LocaleSidKey = 'en_CA';
        oUsr.EmailEncodingKey = 'ISO-8859-1';
        oUsr.ProfileId = '00eF0000000WOiJIAW';
        OUsr.LanguageLocaleKey = 'en_US';
        lUsr.add(oUsr);

 

Best Answer chosen by Admin (Salesforce Developers) 
Shashikant SharmaShashikant Sharma

Do it like this

List<Profile> listProfile = [Select id from Profile];
list<User> lUsr = new list<User>();
for(Profile p : listProfile)
{
        User oUsr = new User();
        oUsr.FirstName = 'James';
        oUsr.LastName = 'Dean';
        oUsr.Email = 'james@dean.com';
        oUsr.Username = 'jdean@jamesdean.com';
        oUsr.Alias = 'jdean';
        oUsr.CommunityNickname = 'j1234';
        OUsr.TimeZoneSidKey = 'America/Denver';
        oUsr.LocaleSidKey = 'en_CA';
        oUsr.EmailEncodingKey = 'ISO-8859-1';
        oUsr.ProfileId = p.id;
        OUsr.LanguageLocaleKey = 'en_US';
        lUsr.add(oUsr);
} 

insert lUsr;

 let me know if any issues in it.