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
Christopher PickingChristopher Picking 

How do I assign a user within my test class??

I need to have a user assigned in order to make this test class actually function. My actual class and trigger work as designed, but the test class fails because it requires a user to be present in order to work. Here is the code I have. I'm very new to apex and coding all together so I'm kinda stuck. 

@isTest
public with sharing class UpdateNCMOwnerHandlerTest
{
public static testMethod void testUpdateNCMOwnerHandler()
{
  List<Non_Conforming_Material__c> nonConformingMaterials = new List<Non_Conforming_Material__c>();
Non_Conforming_Material__c nonConformingMaterial = new Non_Conforming_Material__c(NCM_Stage__c = 'In Process'); //#1
  nonConformingMaterials.add(nonConformingMaterial);
  nonConformingMaterial = new Non_Conforming_Material__c(NCM_Stage__c = 'Resolution'); //#2
  nonConformingMaterials.add(nonConformingMaterial);
  insert nonConformingMaterials;
    }
}
Best Answer chosen by Christopher Picking
Deepak Kumar ShyoranDeepak Kumar Shyoran
As you want to change or set the context for a particular user in test class then you need to use Runas method in your test class use below code inside test class.

For ex:
User u3 = [SELECT Id FROM User WHERE UserName='newuser@testorg.com'];
System.runAs(u3) {

All Answers

ashish kumar 18ashish kumar 18
Hi,

Use the below mentioned code for user creation, then use Sustem.runas(u) as show below.

Profile p = [select id from profile where name='Standard User'];

        User u = new User(alias = 'test123', email='test123@noemail.com',
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
            localesidkey='en_US', profileid = p.Id, country='United States',
            Favorite_Color__c='Pretty Pink',
            timezonesidkey='America/Los_Angeles', username='test123@noemail.com');
        insert u;
System.runas(u){
        ////////////////// write all the logic within this
}
Deepak Kumar ShyoranDeepak Kumar Shyoran
As you want to change or set the context for a particular user in test class then you need to use Runas method in your test class use below code inside test class.

For ex:
User u3 = [SELECT Id FROM User WHERE UserName='newuser@testorg.com'];
System.runAs(u3) {
This was selected as the best answer
Christopher PickingChristopher Picking
Thank you both, The simplicity of Deepaks works best for me in this case.