I created a very simple method on a before insert trigger, that adds the number 11 to a value if a regular user creates a record, But it doesn't add anything if the service user creates it.
So for example, if I create a record and the Internal_Id__c is 100 the result should be 111. If the service user create the record with the same value, it should stay 100.
private static void changeInternalId() {
List < Response__c > survList = [SELECT Id, createdBy.Id, createdBy.Name, Internal_Id__c FROM Response__c WHERE Id in: Trigger.New];
for (Response__c surv: survList) {
if (surv.createdBy.Id != '0053i000002IMP1AAO' && surv.Internal_Id__c != null) {
if (Test.isRunningTest()) {
surv.Internal_Id__c = surv.Internal_Id__c + 11;
}
}
}
}
//test class
Profile p = [SELECT Id FROM Profile WHERE Name = 'Test Profile'];
User regularUser = new User(Alias = 'standt', Email = '[email protected]',
EmailEncodingKey = 'UTF-8', LastName = 'Testing', LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US', ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles', UserName = '[email protected]');
System.runAs(regularUser) {
Response__c surv = new Response__c();
surv.Internal_Id__c = 100;
insert surv;
surv = [SELECT Id, Internal_Id__c, CreatedBy.Id, CreatedBy.Name FROM Response__c WHERE Id =: surv.Id];
System.debug(surv.CreatedBy.Id); //output: 0053B000004Cxz0QAC
System.debug(surv.CreatedBy.Name); // output: Testing
System.assertEquals(111, surv.Internal_Id__c); //failed!! actual value is 100 and not 111
}
User serviceUser = [SELECT Id FROM User WHERE id = '0053i000002IMP1AAO'];
System.runAs(serviceUser) {
Response__c surv = new Response__c();
surv.Internal_Id__c = 120;
insert surv;
surv = [SELECT Id, Internal_Id__c, CreatedBy.Id, CreatedBy.Name FROM Response__c WHERE Id =: surv.Id];
System.debug(surv.CreatedBy.Id); //output: 0053B000004CxkvQAC
System.debug(surv.CreatedBy.Name);//output: service user
System.assertEquals(120, surv.Internal_Id__c); //works!! value remains 120
}