+ Start a Discussion
sachin shah 27sachin shah 27 

How to create user in test class and assign it to contact?

Anilkumar KotaAnilkumar Kota
Hi Sachin ,

Test classes are required for Apex Class and Apex Triggers. Do you have specific code related to Account/Contact.

Find the below links for more information .



Hi Sachin,
/* Fill all mandatory fields */
       user.Username = 'test@samp.com';
       user.Email = 'test@samp.com';
       user.Alias = 'tsamp';
       user.UserRoleId = 'user_role_id_goes_here';
       user.ProfileId = 'user_profile_id_goes_here';
       user.Employment_Start_Date__c = '01/01/2013';
       user.IsActive = false;  // here we are creating inactive user account
           insert user;  // insert the user record
     catch(Exception e)

//Insert Contact
Contact con = new Contact();
con.lastname = 'test';
con.ownerid = user.id;
insert con;
The above code will create a new user and create a contact record with newly created user as owner.
Balayesu ChilakalapudiBalayesu Chilakalapudi
You can use UserInfo.getUserId() to get user id in your test method
Try like this,
Contact con = new Contact();
con.lastname = 'test';
con.ownerid = UserInfo.getUserId();
insert con;

Let us know if it helps
Deepali KulshresthaDeepali Kulshrestha
Hi Sachin,

I've gone through your requirement and you can see the example below  of creating a user:

Profile profileId = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
        User usr = new User(LastName = 'LIVESTON',
                           Alias = 'jliv',
                           Email = 'jason.liveston@asdf.com',
                           Username = 'jason.liveston@asdf.com',
                           ProfileId = profileId.id,
                           TimeZoneSidKey = 'GMT',
                           LanguageLocaleKey = 'en_US',
                           EmailEncodingKey = 'UTF-8',
                          LocaleSidKey = 'en_US'

Contact con=new Contact();

insert con;

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha