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
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 .

http://rainforce.walkme.com/how-to-write-test-class-in-salesforce/

http://blog.shivanathd.com/2013/11/Best-Practices-Test-Class-in-Salesforce.html

https://developer.salesforce.com/forums/?id=906F0000000BS6XIAW
AnjunaAnjuna
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
       try
      {
           insert user;  // insert the user record
       }
     catch(Exception e)
     {
          System.debug(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',
                           FirstName='JASON',
                           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();
con.LastName='LastName';
con.OwnerId=usr.Id;

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
www.kdeepali.com