+ Start a Discussion
Luciano Castro2019Luciano Castro2019 

Classes are failing due to a validation rule update

I created the following validation rule: 

ISCHANGED(Lead_Source_INTL__c) &&
NOT(ISBLANK(PRIORVALUE(Lead_Source_INTL__c))) &&
$Profile.Name <> 'System Administrator' &&
$Profile.Name <> 'Sales Support' &&
$Profile.Name <> 'API User' &&
$Profile.Name <> 'Marketing Administrator' &&
NOT(BEGINS($User.Username, 'giselle.petit@intlfcstone.com'))

However, I cannot deploy it because the class below is failing:

static testMethod void ShouldNotAllowCustomStandardUserToUpdateLeadSource() {
        User u = [SELECT Id FROM User WHERE IsActive = true AND ProfileId = :sObjectCreator.customStandardUserProfileId LIMIT 1];
        Boolean hasValidationError = insertAndUpdateLeadSourceAsUser(u);
        System.assert(hasValidationError);

Unfortunately, my only developer is on vacation :(  and I am not sure what is going on. Please help!
 
Santosh Reddy MaddhuriSantosh Reddy Maddhuri
Hi Luciano,

Can you paste the extact error message and if possible test class. Let me see, if i can correct the class .
Luciano Castro2019Luciano Castro2019
Test Fail 

User-added image

User-added image

/**
 * Created by Al.Hotchkiss on 1/25/2018.
 *
 * Purpose of this test class is to test business logic related to
 * Contacts that does not necessarily reside in a Lead Trigger. For
 * instance, tests for validation rules would be here.
 */

@IsTest
public with sharing class ContactTests {

    static testMethod void ShouldAllowCustomStandardUserToInsertContact() {
        User u = sObjectCreator.createUser();
        u.ProfileId = sObjectCreator.customStandardUserProfileId;
        insert u;
        System.runAs(u) {
            insertContact();
        }
    }

    static testMethod void ShouldAllowAPIUserToInsertContact() {
        User u = [SELECT Id FROM User WHERE Username LIKE 'apiuser@intlfcstone.com%'];
        System.runAs(u) {
            insertContact();
        }
    }

    static testMethod void ShouldAllowEventRegistrantUserToInsertContact() {
        User u = [SELECT Id FROM User WHERE Username LIKE 'event.registrant@intlfcstone.com%'];
        System.runAs(u) {
            insertContact();
        }
    }

    static testMethod void ShouldAllowMarketingAutomationUserToInsertContact() {
        User u = [SELECT Id FROM User WHERE Username LIKE 'marketing.automation@intlfcstone.com%'];
        System.runAs(u) {
            insertContact();
        }
    }

    static testMethod void ShouldNotAllowMarketingAutomationUserToUpdateLeadSourceType() {
        Boolean hasValidationError = insertAndUpdateLeadSourceTypeAsUser('marketing.automation@intlfcstone.com');
        System.assert(hasValidationError);
    }

    static testMethod void ShouldNotAllowCustomStandardUserToUpdateLeadSourceType() {
        User u = [SELECT Id FROM User WHERE IsActive = true AND ProfileId = :sObjectCreator.customStandardUserProfileId LIMIT 1];
        Boolean hasValidationError = insertAndUpdateLeadSourceTypeAsUser(u);
        System.assert(hasValidationError);
    }

    static testMethod void ShouldAllowAPIUserToUpdateLeadSourceType() {
        Boolean hasValidationError = insertAndUpdateLeadSourceTypeAsUser('apiuser@intlfcstone.com');
        System.assert(!hasValidationError);
    }

    static testMethod void ShouldAllowMarketingAdministratorToUpdateLeadSourceType() {
        Profile p = [SELECT Id FROM Profile WHERE Name = 'Marketing Administrator'];
        User u = [SELECT Id FROM User WHERE IsActive = true AND ProfileId = :p.Id LIMIT 1];
        Boolean hasValidationError = insertAndUpdateLeadSourceTypeAsUser(u);
        System.assert(!hasValidationError);
    }

    static testMethod void ShouldAllowEventRegistrantUserToUpdateLeadSourceType() {
        Contact c;
        User u = [SELECT Id FROM User WHERE Username LIKE 'event.registrant@intlfcstone.com%' LIMIT 1];
        String leadSourceTypeBeforeUpdate;
        Boolean hasValidationError = false;
        Boolean hasException = false;

        System.runAs(u) {
            c = insertContact();
            leadSourceTypeBeforeUpdate = c.Lead_Source_Type__c;
            try {
                c.Lead_Source_Type__c = 'Event';
                update c;
            }
            catch (DmlException dex) {
                hasException = true;
                hasValidationError = exceptionContainsFieldValidationError(dex, 'Lead_Source_Type__c');
            }
        }

        c = [SELECT Lead_Source_Type__c FROM Contact WHERE Id = :c.Id];

        System.assert(!hasValidationError && !hasException, 'Validation failed or an exception occurred.');
        System.assertEquals(leadSourceTypeBeforeUpdate, c.Lead_Source_Type__c, 'Lead_Source_Type__c was updated.');
    }

    static testMethod void ShouldNotAllowCustomStandardUserToUpdateLeadSourceTypeFromBlank() {
        User u = [SELECT Id FROM User WHERE IsActive = true AND ProfileId = :sObjectCreator.customStandardUserProfileId LIMIT 1];
        Boolean hasValidationError = insertAndUpdateLeadSourceTypeFromBlankAsUser(u);
        //has to throw validation because the default will be 'broker' and user cannot subsequently change
        System.assert(hasValidationError);
    }

    static testMethod void ShouldNotAllowMarketingAutomationUserToUpdateLeadSourceTypeFromBlank() {
        Boolean hasValidationError = insertAndUpdateLeadSourceTypeFromBlankAsUser('marketing.automation@intlfcstone.com');
                //has to throw validation because the default will be 'broker' and user cannot subsequently change

        System.assert(hasValidationError);
    }

    static testMethod void ShouldAllowEventRegistrantUserToUpdateLeadSourceTypeFromBlank() {
        Boolean hasValidationError = insertAndUpdateLeadSourceTypeFromBlankAsUser('event.registrant@intlfcstone.com');
        System.assert(!hasValidationError);
    }

    static testMethod void ShouldNotAllowMarketingAutomationUserToUpdateLeadSource() {
        Boolean hasValidationError = insertAndUpdateLeadSourceAsUser('marketing.automation@intlfcstone.com');
        System.assert(hasValidationError);
    }

    static testMethod void ShouldNotAllowEventRegistrantUserToUpdateLeadSource() {
        Boolean hasValidationError = insertAndUpdateLeadSourceAsUser('event.registrant@intlfcstone.com');
        System.assert(hasValidationError);
    }

    static testMethod void ShouldNotAllowCustomStandardUserToUpdateLeadSource() {
        User u = [SELECT Id FROM User WHERE IsActive = true AND ProfileId = :sObjectCreator.customStandardUserProfileId LIMIT 1];
        Boolean hasValidationError = insertAndUpdateLeadSourceAsUser(u);
        System.assert(hasValidationError);
    }

    static testMethod void ShouldAllowAPIUserToUpdateLeadSource() {
        Boolean hasValidationError = insertAndUpdateLeadSourceAsUser('apiuser@intlfcstone.com');
        System.assert(!hasValidationError);
    }

    static testMethod void ShouldAllowMarketingAdministratorToUpdateLeadSource() {
        Profile p = [SELECT Id FROM Profile WHERE Name = 'Marketing Administrator'];
        User u = [SELECT Id FROM User WHERE IsActive = true AND ProfileId = :p.Id LIMIT 1];
        Boolean hasValidationError = insertAndUpdateLeadSourceAsUser(u);
        System.assert(!hasValidationError);
    }

    static Contact insertContact() {
        Contact c = sObjectCreator.createContact();
        c.Lead_Source_Type__c = 'Broker';
        c.Lead_Source_INTL__c = 'Lead Source Value';
        insert c;
        c = [SELECT Id, Name, Lead_Source_INTL__c, Lead_Source_Type__c, FirstName, LastName, AccountId, Phone, Email FROM Contact WHERE Id = :c.Id];
        return c;
    }

    static Contact insertContactWithBlankLeadSourceType() {
        Contact c = sObjectCreator.createContact();
        c.Lead_Source_INTL__c = 'Lead Source Value';
        insert c;
        c = [SELECT Id, Name, Lead_Source_INTL__c, Lead_Source_Type__c, FirstName, LastName, AccountId, Phone, Email FROM Contact WHERE Id = :c.Id];
        return c;
    }

    static Boolean insertAndUpdateLeadSourceTypeAsUser(User u) {
        Boolean hasValidationError = false;

        System.runAs(u) {
            Contact c = insertContact();
            c.Lead_Source_Type__c = 'Event';
            try {
                update c;
            }
            catch (DmlException dex) {
                System.debug(dex);
                hasValidationError = exceptionContainsFieldValidationMessage(dex, 'Lead Source Type');
            }
        }

        return hasValidationError;
    }

    static Boolean insertAndUpdateLeadSourceTypeAsUser(String userName) {
        User u = [SELECT Id FROM User WHERE Username LIKE :userName+ '%'];
        return insertAndUpdateLeadSourceTypeAsUser(u);
    }

    static Boolean insertAndUpdateLeadSourceTypeFromBlankAsUser(User u) {
        Boolean hasValidationError = false;

        System.runAs(u) {
            Contact c = insertContactWithBlankLeadSourceType();
            c.Lead_Source_Type__c = 'Event';
            try {
                update c;
            }
            catch (DmlException dex) {
                System.debug(dex);
                hasValidationError = exceptionContainsFieldValidationError(dex, 'Lead_Source_Type__c');
            }
        }

        return hasValidationError;
    }

    static Boolean insertAndUpdateLeadSourceTypeFromBlankAsUser(String userName) {
        User u = [SELECT Id FROM User WHERE Username LIKE :userName+ '%'];
        return insertAndUpdateLeadSourceTypeFromBlankAsUser(u);
    }

    static Boolean insertAndUpdateLeadSourceAsUser(User u) {
        Boolean hasValidationError = false;

        System.runAs(u) {
            Contact c = insertContact();
            c.Lead_Source_INTL__c = 'Lead Source Update';
            try {
                update c;
            }
            catch (DmlException dex) {
                System.debug(dex);
                hasValidationError = exceptionContainsFieldValidationError(dex, 'Lead_Source_INTL__c');
            }
        }

        return hasValidationError;
    }

    static Boolean insertAndUpdateLeadSourceAsUser(String userName) {
        User u = [SELECT Id FROM User WHERE Username LIKE :userName+ '%'];
        return insertAndUpdateLeadSourceAsUser(u);
    }

    static Boolean exceptionContainsFieldValidationError(DmlException dex, String fieldName) {
        System.debug('Testing validation: ' + fieldName + ', Exception: ' + dex);
        Boolean hasValidationError = false;

        for (Integer i = 0; i < dex.getNumDml(); i++) {
            List<String> fields = dex.getDmlFieldNames(i);
            System.debug('DML Ex Field Names: ' + fields);

            for (String s : fields) {
                if (s.equalsIgnoreCase(fieldName)) {
                    if (dex.getDmlType(i) == System.StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION) {
                        hasValidationError = true;
                        break;
                    }
                }
            }
            if (hasValidationError) break;
        }
        return hasValidationError;
    }

    static Boolean exceptionContainsFieldValidationMessage(DmlException dex, String searchText) {
        Boolean hasValidationError = false;

        for (Integer i = 0; i < dex.getNumDml(); i++) {
            String msg = dex.getDmlMessage(i);
            if (msg.containsIgnoreCase(searchText)) {
                hasValidationError = true;
                break;
            }
        }
        return hasValidationError;
    }
}
Santosh Reddy MaddhuriSantosh Reddy Maddhuri

Hi Luciano,

to debug further i need to look at the profile thats called for in this class " sObjectCreator" and in this method "createUser()". Analyzing this will fix first 2 failures from screenshot(Line 123 and line). For rest of the errors please try to modify the validation as follows

ISCHANGED(Lead_Source_INTL__c) &&
NOT(ISBLANK(PRIORVALUE(Lead_Source_INTL__c))) &&
$Profile.Name <> 'System Administrator' &&
$Profile.Name <> 'Sales Support' &&
$Profile.Name <> 'API User' &&
$Profile.Name <> 'Marketing Administrator' &&
NOT(BEGINS($User.Username, 'giselle.petit@intlfcstone.com')) &&
NOT(BEGINS($User.Username, 'marketing.automation@intlfcstone.com')) &&
NOT(BEGINS($User.Username, 'event.registrant@intlfcstone.com'))

Hope this helps. Try adding modifications and run the test class again and see if it throws any error. If yes, then i need to look at sObjectCreator class.


Thanks & Regards,

Santosh.

Luciano Castro2019Luciano Castro2019
Hi Santosh, 

Thank you for taking a look at this. I saw the modified validation but you know what bugs me? Both marketing.automation and event.registrant are part of the API User profile. 

Please see class for sObjectCreator:


/*
 *    This class contains helpers you can use in your testMethods.
 *
 *  The sObjects created here should have the bare minimum of fields needed to be inserted.
 *
 *  PLEASE NOTE: Additional fields required for your testMethods should be added to in YOUR testMethods, not here.
 *  --------------------------------------------------------------------------------------------------------------
 */
@IsTest(SeeAllData=true)
public with sharing class sObjectCreator {

    static {
        getUserProfiles();
    }
    
    public static Id standardUserProfileId;
    public static Id systemAdminUserProfileId;
    public static Id customStandardUserProfileId;
    public static Id managementStandardUserProfileId;
    public static Id executiveStandardUserProfileId;
    public static Id customerCommunityUserProfileId; // Standard SF Profile
    public static Id customerCommunityStandardUserProfileId;  // Custom Profile
    public static Id companyCommunityUserProfileId;
    public static Id chatterFreeUserProfileId;
    public static Id apiUserProfileId;
    public static Id marketingAdminUserProfileId;
    public static Id salesSupportUserProfileId;

    private static void getUserProfiles(){
        List<Profile> Profile_List = [
                                    SELECT
                                        Id,
                                        Name
                                    FROM Profile
                                    WHERE Name IN (
                                        :GlobalConstants.PROFILE_NAME_SYSTEM_ADMIN,
                                        :GlobalConstants.PROFILE_NAME_STANDARD,
                                        :GlobalConstants.PROFILE_NAME_CUSTOM_STANDARD,
                                        :GlobalConstants.PROFILE_NAME_MGMT_STANDARD,
                                        :GlobalConstants.PROFILE_NAME_EXEC_STANDARD,
                                        :GlobalConstants.PROFILE_NAME_CUST_COMM_PLUS_LOGIN,
                                        :GlobalConstants.PROFILE_NAME_CUST_COMM_PLUS_LOGIN_STANDARD,
                                        :GlobalConstants.PROFILE_NAME_COMPANY_COMMUNITIES,
                                        :GlobalConstants.PROFILE_NAME_CHATTER_FREE,
                                        :GlobalConstants.PROFILE_NAME_API,
                                        :GlobalConstants.PROFILE_NAME_MARKETING_ADMIN,
                                        :GlobalConstants.PROFILE_NAME_SALES_SUPPORT
                                    )];
                    
        for(Profile p : Profile_List){
            if (p.Name == GlobalConstants.PROFILE_NAME_SYSTEM_ADMIN) systemAdminUserProfileId = p.Id;
            if (p.Name == GlobalConstants.PROFILE_NAME_STANDARD) standardUserProfileId = p.Id;
            if (p.Name == GlobalConstants.PROFILE_NAME_CUSTOM_STANDARD) customStandardUserProfileId = p.Id;
            if (p.Name == GlobalConstants.PROFILE_NAME_MGMT_STANDARD) managementStandardUserProfileId = p.Id;
            if (p.Name == GlobalConstants.PROFILE_NAME_EXEC_STANDARD) executiveStandardUserProfileId = p.Id;
            if (p.Name == GlobalConstants.PROFILE_NAME_CUST_COMM_PLUS_LOGIN) customerCommunityUserProfileId = p.Id; // Standard SF Profile
            if (p.Name == GlobalConstants.PROFILE_NAME_CUST_COMM_PLUS_LOGIN_STANDARD) customerCommunityStandardUserProfileId = p.Id; // Custom Profile
            if (p.Name == GlobalConstants.PROFILE_NAME_COMPANY_COMMUNITIES) companyCommunityUserProfileId = p.Id;
            if (p.Name == GlobalConstants.PROFILE_NAME_CHATTER_FREE) chatterFreeUserProfileId = p.Id;
            if (p.Name == GlobalConstants.PROFILE_NAME_API) apiUserProfileId = p.Id;
            if (p.Name == GlobalConstants.PROFILE_NAME_MARKETING_ADMIN) marketingAdminUserProfileId = p.Id;
            if (p.Name == GlobalConstants.PROFILE_NAME_SALES_SUPPORT) salesSupportUserProfileId = p.Id;
        }
    }
    
    //******************************************************************************************
    //                       Standard Object and RecordTypes Creation
    //******************************************************************************************
    public static User createUser(){
        String tag = GlobalHelper.getTag(10);

        User userObject = new User();
        userObject.LastName = 'Test' + tag;
        String userName = 'test' + tag + '@test.com';
        userObject.Username = userName;
        userObject.Email = userName;
        userObject.Alias = 'test' + tag.left(4);
        userObject.CommunityNickname = 'test' + tag;
        userObject.TimeZoneSidKey = 'America/Chicago';
        userObject.ProfileId = standardUserProfileId;
        userObject.IsActive = true;
        userObject.EmailEncodingKey = 'ISO-8859-1';
        userObject.LocaleSidKey = 'en_US';
        userObject.LanguageLocaleKey = 'en_US';
        return userObject;
    }

    public static User createCustomerCommunitiesUser(Contact c) {
        User newUser = new User (
                LastName = 'CustCommUser'+GlobalHelper.getTag(5),
                Alias = GlobalHelper.getTag(6),
                Email = c.Email,
                Username = c.Email,
                CommunityNickname = GlobalHelper.getTag(6),
                TimeZoneSidKey = 'America/Chicago',
                LocaleSidKey = 'en_US',
                LanguageLocaleKey = 'en_US',
                EmailEncodingKey = 'ISO-8859-1',
                ContactId = c.Id,
                ProfileId = customerCommunityStandardUserProfileId
        );
        return newUser;
    }

    public static testMethod void testUser(){
        User UserObject = sObjectCreator.createUser();
        insert UserObject;
    }

    public static Lead createLead(){
        Lead LeadObject = new Lead();
        LeadObject.Company = 'Test Company' + GlobalHelper.getTag();
        LeadObject.FirstName = 'First Name'+ GlobalHelper.getTag();
        LeadObject.LastName = 'Last Name'+ GlobalHelper.getTag();
        LeadObject.Country = 'United States';
        LeadObject.pi__Url__c = 'http://wwww.example.com';
        LeadObject.Duplicate_Detection__c = 'Disabled';
        return LeadObject;
    }

    public static testMethod void testInsertLead(){
        Lead LeadObject = sObjectCreator.createLead();
        insert LeadObject;
    }

    public static Account createAccount(){
        Account AccountObject = new Account();
        AccountObject.Name = 'Test Account' + GlobalHelper.getTag();
        AccountObject.BillingCity = 'New York';
        AccountObject.BillingStateCode = 'NY';
        AccountObject.BillingCountryCode = 'US';
        return AccountObject;
    }

    public static testMethod void testInsertAccount(){
        Account AccountObject = sObjectCreator.createAccount();
        insert AccountObject;
    }

    public static Contact createContact(){
        Contact ContactObject = new Contact();
        ContactObject.FirstName = 'Test FirstName';
        ContactObject.LastName = 'Test LastName' + GlobalHelper.getTag();
        ContactObject.Email = 'test@example.com';
        ContactObject.pi__Url__c = 'http://wwww.example.com';
        ContactObject.MailingCity = 'New York';
        ContactObject.MailingStateCode = 'NY';
        ContactObject.MailingCountryCode = 'US';
        ContactObject.Duplicate_Detection__c = 'Disabled';
        return ContactObject;
    }

    public static testMethod void testInsertContact(){
        Account AccountObject = sObjectCreator.createAccount();
        insert AccountObject;
        
        Contact ContactObject = sObjectCreator.createContact();
        ContactObject.AccountId = AccountObject.Id;
        insert ContactObject;
    }

    public static Opportunity createOpportunity(){
        Opportunity OpportunityObject = new Opportunity();
        OpportunityObject.Name = 'Test Opportunity';
        OpportunityObject.StageName = 'Prospecting';
        OpportunityObject.CloseDate = System.today().addDays(7);
        return OpportunityObject;
    }

    public static testMethod void testInsertOpportunity(){
        Account AccountObject = sObjectCreator.createAccount();
        insert AccountObject;
        
        Opportunity OpportunityObject = sObjectCreator.createOpportunity();
        OpportunityObject.AccountId = AccountObject.Id;
        insert OpportunityObject;
    }

    public static OpportunityContactRole createOpportunityContactRole(){
        OpportunityContactRole OpportunityContactRoleObject = new OpportunityContactRole();
        OpportunityContactRoleObject.Role = 'Decision Maker';
        OpportunityContactRoleObject.IsPrimary = true;
        return OpportunityContactRoleObject;
    }

    public static testMethod void testOpportunityContactRole(){
        Account AccountObject = sObjectCreator.createAccount();
        insert AccountObject;
        
        Contact ContactObject = sObjectCreator.createContact();
        ContactObject.AccountId = AccountObject.Id;
        insert ContactObject;
        
        Opportunity OpportunityObject = sObjectCreator.createOpportunity();
        OpportunityObject.AccountId = AccountObject.Id;
        insert OpportunityObject;

        OpportunityContactRole OpportunityContactRoleObject = sObjectCreator.createOpportunityContactRole();
        OpportunityContactRoleObject.OpportunityId = OpportunityObject.Id;
        OpportunityContactRoleObject.ContactId = ContactObject.Id;
        insert OpportunityContactRoleObject;
    }

    public static OpportunityLineItem createOpportunityLineItem(){
        OpportunityLineItem OpportunityLineItemObject = new OpportunityLineItem();
        return OpportunityLineItemObject;
    }

    public static testMethod void testOpportunityLineItem(){
        String StandardPricebookId = [SELECT Id FROM Pricebook2 WHERE IsStandard = TRUE LIMIT 1].Id;
        
        Product2 Product2Object = sObjectCreator.createProduct2();
        Product2Object.ProductCode = 'Code';
        Product2Object.Name = 'Product Name';
        insert Product2Object;

        PricebookEntry stdPricebookEntryObject = sObjectCreator.createPricebookEntry();
        stdPricebookEntryObject.Pricebook2Id = StandardPricebookId;
        stdPricebookEntryObject.Product2Id = Product2Object.Id;
        stdPricebookEntryObject.UnitPrice = 2.5;
        insert stdPricebookEntryObject;
        
        Opportunity OpportunityObject = sObjectCreator.createOpportunity();
        insert OpportunityObject;

        OpportunityLineItem OpportunityLineItemObject = sObjectCreator.createOpportunityLineItem();
        OpportunityLineItemObject.PricebookEntryId = stdPricebookEntryObject.Id;
        OpportunityLineItemObject.OpportunityId = OpportunityObject.Id;
        OpportunityLineItemObject.Quantity = 1;
        OpportunityLineItemObject.UnitPrice = 2.5;
        insert OpportunityLineItemObject;
    }

    public static Case createCase(){
        Case CaseObject = new Case();
        return CaseObject;
    }

    public static testMethod void testInsertCase(){
        Case CaseObject = sObjectCreator.createCase();
        insert CaseObject;
    }

    public static Contract createContract(){
        Contract ContractObject = new Contract();
        return ContractObject;
    }

    public static testMethod void testInsertContract(){
        Account AccountObject = sObjectCreator.createAccount();
        insert AccountObject;
        
        Contract ContractObject = sObjectCreator.createContract();
        ContractObject.AccountId = AccountObject.Id;
        ContractObject.StartDate = System.today();
        insert ContractObject;
    }

    public static Task createTask(){
        Task TaskObject = new Task();
        TaskObject.Subject = 'Test Task';
        return TaskObject;
    }

    public static testMethod void testInsertTask(){
        Task TaskObject = sObjectCreator.createTask();
        insert TaskObject;
    }

    public static Event createEvent(){
        Event EventObject = new Event();
        EventObject.Subject = 'Test Event';
        EventObject.DurationInMinutes = 60;
        EventObject.ActivityDate = System.today().addDays(2);
        EventObject.ActivityDateTime = System.now().addDays(2);
        return EventObject;
    }

    public static testMethod void testInsertEvent(){
        Event EventObject = sObjectCreator.createEvent();
        insert EventObject;
    }

    public static Pricebook2 createPricebook2(){
        Pricebook2 Pricebook2Object = new Pricebook2();
        Pricebook2Object.Name = 'Test';
        Pricebook2Object.IsActive = true;
        return Pricebook2Object;
    }

    public static testMethod void testPricebook2(){
        Pricebook2 Pricebook2Object = sObjectCreator.createPricebook2();
        insert Pricebook2Object;
    }

    public static Product2 createProduct2(){
        Product2 Product2Object = new Product2();
        Product2Object.IsActive = true;
        return Product2Object;
    }

    public static testMethod void testProduct2(){
        Product2 Product2Object = sObjectCreator.createProduct2();
        Product2Object.ProductCode = 'Code';
        Product2Object.Name = 'Product Name';
        Product2Object.Family = 'Family';
        insert Product2Object;
    }

    public static PricebookEntry createPricebookEntry(){
        PricebookEntry PricebookEntryObject = new PricebookEntry();
        PricebookEntryObject.IsActive = true;
        return PricebookEntryObject;
    }

    public static testMethod void testPricebookEntry(){
        String StandardPricebookId = [SELECT Id FROM Pricebook2 WHERE IsStandard = TRUE].Id;

        Pricebook2 Pricebook2Object = sObjectCreator.createPricebook2();
        insert Pricebook2Object;
        
        Product2 Product2Object = sObjectCreator.createProduct2();
        Product2Object.ProductCode = 'Code';
        Product2Object.Name = 'Product Name';
        insert Product2Object;
        
        PricebookEntry stdPricebookEntryObject = sObjectCreator.createPricebookEntry();
        stdPricebookEntryObject.Pricebook2Id = StandardPricebookId;
        stdPricebookEntryObject.Product2Id = Product2Object.Id;
        stdPricebookEntryObject.UnitPrice = 2.5;
        insert stdPricebookEntryObject;
        
        PricebookEntry PricebookEntryObject = sObjectCreator.createPricebookEntry();
        PricebookEntryObject.Pricebook2Id = Pricebook2Object.Id;
        PricebookEntryObject.Product2Id = Product2Object.Id;
        PricebookEntryObject.UnitPrice = 2.5;
        insert PricebookEntryObject;
    }

    //******************************************************************************************
    //                           Custom Object  Creation
    //******************************************************************************************

    public static void createExternalUrls() {
        External_Urls__c url = new External_Urls__c();        
        url.CSC_Application_Url__c = 'http://www.google.com';
        url.Open_CSC_Account_Url__c = 'http://www.opencscapp.com';
        url.Connect_Signup_Url__c = 'https://fakeconnect.intlfcstone.com';
        url.Manage_Security_Groups_Url__c = 'https://fakesecgroups.intlfcstone.com';
        insert url;
    }

    public static Company_Account__c createCompanyAccount() {
        Company_Account__c ca = new Company_Account__c();        
        ca.Account_Number__c = 'ABC123';
        Account co = sObjectCreator.createAccount();        
        ca.Company__c = co.Id;
        ca.Source_Account_Owner__c = 'John Doe';
        ca.CSC_Application_Id__c = 'TESTAPPID123';
        ca.Date_Opened__c = Date.today();
        ca.Source_System__c = 'Salesforce';
        ca.Name = 'TESTACCT123';
        return ca;
    }
    
    static testmethod void testCreateCompanyAccount() {
        Company_Account__c ca = sObjectCreator.createCompanyAccount();
        insert ca;
    }

    public static Company_Account_Volume__c createCompanyAccountVolume() {
        Company_Account_Volume__c cav = new Company_Account_Volume__c(); 
        cav.Company_Account__c = sObjectCreator.createCompanyAccount().Id;
        cav.ExternalAccountVolumeId__c = GlobalHelper.getTag();
        cav.Business_Date__c = System.today();
        cav.Last_Transaction_Date__c = System.today();
        cav.Transaction_Count__c = 1;
        cav.Volume__c = 1;
        return cav;
    }
}
Santosh Reddy MaddhuriSantosh Reddy Maddhuri
Hi Luciano,

I understand the catch here.I cannot be much help why the code did include things such a way. But we can try this . Please find the profile id /name thats mentioned in " GlobalConstants.PROFILE_NAME_CUSTOM_STANDARD" and include that profile name to your original validation rule that way line 44, line 95, line 123 will go away.

Original  :

ISCHANGED(Lead_Source_INTL__c) &&
NOT(ISBLANK(PRIORVALUE(Lead_Source_INTL__c))) &&
$Profile.Name <> 'System Administrator' &&
$Profile.Name <> 'Sales Support' &&
$Profile.Name <> 'API User' &&
$Profile.Name <> 'Marketing Administrator' &&
NOT(BEGINS($User.Username, 'giselle.petit@intlfcstone.com'))


version 1 :

ISCHANGED(Lead_Source_INTL__c) &&
NOT(ISBLANK(PRIORVALUE(Lead_Source_INTL__c))) &&
$Profile.Name <> 'System Administrator' &&
$Profile.Name <> 'Sales Support' &&
$Profile.Name <> 'API User' &&
$Profile.Name <> 'Marketing Administrator' &&
$Profile.Name <> (GlobalConstants.PROFILE_NAME_CUSTOM_STANDARD - what ever it contains.) &&
NOT(BEGINS($User.Username, 'giselle.petit@intlfcstone.com')) &&
(
NOT(BEGINS($User.Username, 'marketing.automation@intlfcstone.com')) ||
NOT(BEGINS($User.Username, 'event.registrant@intlfcstone.com'))
)
 


version 2 :

ISCHANGED(Lead_Source_INTL__c) &&
NOT(ISBLANK(PRIORVALUE(Lead_Source_INTL__c))) &&
$Profile.Name <> 'System Administrator' &&
$Profile.Name <> 'Sales Support' &&
$Profile.Name <> 'API User' &&
$Profile.Name <> 'Marketing Administrator' &&
$Profile.Name <> (GlobalConstants.PROFILE_NAME_CUSTOM_STANDARD - what ever it contains.) &&
NOT(BEGINS($User.Username, 'giselle.petit@intlfcstone.com')) &&
NOT(BEGINS($User.Username, 'marketing.automation@intlfcstone.com')) &&
NOT(BEGINS($User.Username, 'event.registrant@intlfcstone.com')) 
Luciano Castro2019Luciano Castro2019
If I add the Custom Standard profile in the validation, then the validation rule will not fire for that profile.
 
Santosh Reddy MaddhuriSantosh Reddy Maddhuri
I understand, but that profile is being called in the test class and being run on a user with that profile. Another alternative would be on the below lines.

1. Create a test user for that profile. 
2. change line of code to include the above user in test class  

line :    User u = [SELECT Id FROM User WHERE IsActive = true AND ProfileId = :sObjectCreator.customStandardUserProfileId LIMIT 1];
modify :    User u = [SELECT Id FROM User WHERE IsActive = true AND ProfileId = :sObjectCreator.customStandardUserProfileId and Name Like  <Testuser%> LIMIT 1];

3. Then include line in validation to not include that test user for the exception.

This change will cost another user license.But code will run without assertion failures.

Or the default way woould be revamp the code to include the current validation rule.


 
Luciano Castro2019Luciano Castro2019
Good Morning Santosh

If I am understanding correctly, the reason why this is failing is that the validation rule prevents the user from Custom Standard profile to change a value on a picklist field but the class is allowing? Is that correct?
Santosh Reddy MaddhuriSantosh Reddy Maddhuri
Hi Luciano,

Yes, your validation rule has a run-in situation with the test class. Let me try to explain the run-in/ race condition.
1. Your validation rule will not throw exception on certain usernames used in test class.
2. Test class has usernames which should assert that they have validation error.

Example : marketing or event register user does not or will not be stopped by validation rule, but it is being stopped by Assertion of test class.

One ugly way to circumvent this issue, is to comment the assertions.


Hope this helps!