We have a managed package install in our org. When I create an opportunity, at a certain stage, I need to create a record of that managed package. For this we define validation rule for certain stages.
In the test class, when I create an opportunity record and reach a certain stage, it throws a validation error.
The Problem is in the test class we don't know how to create a managed package object record data (it refers to an apex class which is part of a managed package).
In order to bypass the validation rule, I created a checkbox field on the User object. In the validation rule, I always check the value as false.
$User.BypassValidation__c=false
So If i manually set the BypassValidation__c to true then it bypasses the validation rule. In order to bypass the validation rule in the test class, I made a boolean variable:
public class TriggerDataFactory
{
global static Boolean bypassValidation {
get {
return bypassValidation;
}
set{
system.debug('calling set');
User currentUser = [select BypassValidation__c from User where Id = :UserInfo.getUserId()];
currentUser.BypassValidation__c=bypassValidation;
system.debug('Bypass Apex Value:'+bypassValidation);
}
}
}
In the test class, I create an Opportunity record and before updating the stage, I am setting the variable value as true so that it allows me to bypass validation rule:
@isTest public class OpportunityTest{
@isTest static void testMethod(){
Profile p = [SELECT Id FROM profile WHERE name='System Administrator'];
User usr = TestDataFactory.createUser('Test', 'User', '[email protected]', p.Id, true);
system.runAs(usr){
Opportunity opt=new Opportunity(
Name='Test Opt'
);
insert opt;
Opportunity op=[Select id from Opportunity where Id=:opt.Id];
TriggerDataFactory.bypassValidation=true; //set the value to true so that validtion rule should not enforced.
op.Stage='Stage 2';
update op;
TriggerDataFactory.bypassValidation=false; //Reset to False
}
}
}
But when I run the test class, it still enforces the validation rule. When I check the debug log, I found that Bypass Apex Value: is null, hence I cannot assign/set the value to true.
Can someone please suggest me what I am missing here?