I have a test class where I need to create a record in an object before performing the test.
The only issue I am having is that one of the fields in the test record is a lookup to a User, in order to populate that field I am using the below -
List<user> currentuser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId() LIMIT 1];
String strcurrentuser = currentuser[0].Id;
Then passing strcurrentuser to the field in record creation. It doesnt matter what User is used, any user is fine and so I assumed the executing user would work.
Can anyone advise why this wouldnt work, the error I recieve is below.
14:03:24:291 FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, <FIELDNAME>: id value of incorrect type: a1a25000003QeAiAAK: [FIELDNAME__c]
Try like this:
Global class AS_UpdateSession implements Schedulable {
global void execute(SchedulableContext SC) {
list<Session__c > lstTargetstats = [select id, CurrentPerformance1__c, CurrentPerformance2__c from Session__c WHERE DateOfReview__c = TODAY];
if(lstTargetstats.size() > 0 ){
for(Session__c lstStats : lstTargetStats){
lstStats.UpdatedCurrentPerformance1__c = lstStats.CurrentPerformance1__c;
lstStats.UpdatedCurrentPerformance2__c = CurrentPerformance2__c;
}
System.debug(lstTargetstats);
update lstTargetstats;
}
}
}
Test Class:public class AS_UpdateSessionTEST {
static testMethod void testAS_UpdateSession(){
String CRON_EXP = '0 0 0 15 3 ? 2022';
Session__c testSessObj = new Session__c();
testSessObj.TypeofSession__c = 'Training';
testSessObj.Email_Sent__c = 'No';
testSessObj.DateOfReview__c = system.today();
testSessObj.SessionUser__c = UserInfo.getUserId();
insert testSessObj;
Test.startTest();
// Schedule the test job
String jobId = System.schedule('ScheduledApexTest', CRON_EXP, new AS_UpdateSession());
Test.stopTest();
/* You can do your assertions here if you wish to */
}
}
The testing of Schedulable classes is done in a different manner.
I would recommend reading this: https://trailhead.salesforce.com/en/content/learn/modules/asynchronous_apex/async_apex_scheduled