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
pooja chauchanpooja chauchan 

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 pooja chauchan
Gaurav NirwalGaurav Nirwal
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

Gaurav NirwalGaurav Nirwal
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
pooja chauchanpooja chauchan
thanks