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
Shraddha D GuptaShraddha D Gupta 

Need help in coding !!

Hi All,

I am not a developer and I am trying to copy one existing trigger and test class from the Org and while running the Test Class getting below error- 

System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, State/Province is required for Australia, United States and Canada.: []

I even have included the BillingState in the Account creation to so that validation rule do not trigger. But still no luck. Can anyone help me in reviewing the below codes? 

APEX Trigger-
trigger limitCreationsFromZoominfo on Contact (before insert) {
//This trigger limit to 25 the number of contacts that can be created from Zoominfo per person per month (#33899)
//We can detect that the Contact comes from Zoominfo because: LeadSource = "Zoominfo"
//We need to filter the existing contacts (for the count operation) using the fields: 
//  CreatedBy = <same user> 
//  CreatedDate = <in the last 30 days> 
//  LeadOrigin = "Zoominfo"
    
    
//  Users with roles "System Administrator", "Denodo Systems Integration" or "Operations Supervisor" should not be affected by this rule.
    Id profileId = UserInfo.getProfileId();
    String profileName=[Select Id, Name from Profile where Id=:profileId].Name; 
    if ( !profileName.contains('Operations Supervisor') && !profileName.contains('System Administrator') 
            && !profileName.contains('Denodo Systems Integration')){
            
            String userId = UserInfo.getUserId();
            Datetime limitDate = System.now().addDays(-30);                            
            List<Contact> contactsToInsertFromZoominfo = new List<Contact>();
            for(Contact contactToInsert : System.Trigger.new){
                if (contactToInsert.LeadSource == 'Zoominfo'){
                    contactsToInsertFromZoominfo.add(contactToInsert);
                }
            }
            //if there are insertions from Zoominfo, check the limit
            if (contactsToInsertFromZoominfo.size() > 0) {
                List<AggregateResult> currentContactsZoominfo = [SELECT Count(Id) currentContacts FROM Contact 
                                      WHERE Lead_Origin__c ='Zoominfo' and CreatedDate >= :limitDate and CreatedById = :userId];
                for (Contact contactToInsert : contactsToInsertFromZoominfo) {
                    if ( (Integer.valueOf(currentContactsZoominfo.get(0).get('currentContacts')) + contactsToInsertFromZoominfo.size()) > 25 ){
                        contactToInsert.addError('You can not import more than 25 contacts from Zoominfo in 30 days.');                        
                    }   
                }
                             
            }    
            
     }
    
      
}




APEX Class Test -

/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 * 
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class limitCreationsFromZoominfoTest {
    static testMethod void myUnitTest() {
        Test.startTest();

        Profile pISS = [SELECT Id FROM Profile WHERE Name='Inside Sales Specialist'];               
        User userISS = new User(Alias = 'userISS', UserName='newuserISS@relatedtotest.com', Email = 'test2@relatedtotest.com', 
                             EmailEncodingKey='UTF-8', FirstName = 'testuser2', LastName = 'ISS', ProfileId = pISS.Id,
                             TimeZoneSidKey='America/Los_Angeles',  LocaleSidKey='en_US', LanguageLocaleKey='en_US');           
        insert userIss;

        System.runAs(userISS){
            // Seed the database with some accounts, and make sure they can be bulk inserted successfully.
            Account account1 = new Account(Name = 'Test1RelatedTo Inc.', BillingCountry = 'United States', BillingState = 'California');
            Account[] accts = new Account[] {account1};
            insert accts;
            
            List<Contact> contacts = new List<Contact>();
            for (Integer i =0 ; i < 26; i++){
                String emailc = 'test' + i + '@relatedtotest.com';
                contacts.add(new Contact(LastName='Test1', AccountId=account1.Id, Email=emailc, MailingCountry = 'United States', MailingState = 'California', LeadSource='Zoominfo'));
            }
            contacts.add(new Contact(LastName='Test4', AccountId=account1.Id, Email='testa@relatedtotest.com', MailingCountry = 'United States', MailingState = 'California', LeadSource='Other'));
            contacts.add(new Contact(LastName='Test5', AccountId=account1.Id, Email='testb@relatedtotest.com', MailingCountry = 'United States', MailingState = 'California', LeadSource='Web'));
            
            try{
                insert contacts;  
                System.assert(false);
            } catch (DmlException e) {     
                System.assert(e.getNumDml() == 101); 
                System.assert(e.getDmlMessage(0).contains('You can not import more than 25 contacts from Zoominfo in 30 days.'));               
            }
                                  
        }
                    
                             
        Test.stopTest();
    }       
}

 

Any help would be much appreciated. 

Andrew GAndrew G
Adjust the Account data to include the Province/State field data

Go to the Account record in Setup.  Go to the Validations section and find the Validation.  See what field is actually being tested in Validation.  Update the Test data to include that value. 

It may be that the validation is firing on the physical address, not the billing address field.

Or, change the Test data to not include one the countries that fires the validation:
// Seed the database with some accounts, and make sure they can be bulk inserted successfully.
            Account account1 = new Account(Name = 'Test1RelatedTo Inc.', BillingCountry = 'Mexico', BillingState = 'Chihuahua');
            Account[] accts = new Account[] {account1};
            insert accts;

regards
Andrew
Shraddha D GuptaShraddha D Gupta
Hi Andrew,

Thanks so much for your help!

I am using that field(BillingState) in the test data to feed for Account- 

            Account account1 = new Account(Name = 'Test1RelatedTo Inc.', BillingCountry = 'United States', BillingState = 'California');

and now I am getting this error-

System.AssertException: Assertion Failed

Any idea what I am doing wrong here? Also, if possible, could you please review the trigger and test class? 

Best,
Shraddha
Andrew GAndrew G
Do you have a line number for which Assert is Failing?

I would run some debug statements to check what is being passed so you can determine which assert is failing
 
try{
                insert contacts;  
System.debug('**** debug - i should not be here');
                System.assert(false);
            } catch (DmlException e) {    
System.debug('**** debug - full error list : ' + e );

System.debug('**** debug - error num; ' + e.getNumDml()); 
                System.assert(e.getNumDml() == 101); 

System.debug('**** debug - error msg; ' + e.getDmlMessage(0)); 

                System.assert(e.getDmlMessage(0).contains('You can not import more than 25 contacts from Zoominfo in 30 days.'));               
            }

Run the test, check the debug logs and work out what is happening.  

I suspect the issue is this line
System.assert(e.getNumDml() == 101);
at a desk check, i think the number will be 78, not 101

regards
Andrew
 
Shraddha D GuptaShraddha D Gupta
Hi Andrew,

I added the debugs as you mentioned and also did changed the number 78 but still got the same error at this very line -
System.assert(e.getNumDml() == 78);

09:58:36:261 USER_DEBUG [52]|DEBUG|**** debug - full error list : System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, You can not import more than 25 contacts from Zoominfo in 30 days.: []

09:58:36:261 USER_DEBUG [53]|DEBUG|**** debug - error num; 26

User-added image

I did get these debug errors as well. 

Thanks!
 
Andrew GAndrew G
Ok, just re-read your test class, and yes, 26 would be the error number as you are trying to insert 26 zoominfo records, the additional records have a different source.

Try adjusting that count number and run your test.  The other statement should still equate ok as you are using the contains method.

regards

Andrew
 
Shraddha D GuptaShraddha D Gupta
Hi Andrew,

Okay , so I did try with below changes in Test Class -

for (Integer i =0 ; i < 24; i++)

System.assert(e.getNumDml() == 101); 

MailingCountryCode = 'IN',

but now it is failing at -- System.assert(false);

with the debug log -
09:24:25:686 USER_DEBUG [49]|DEBUG|**** debug - i should not be here

The motto behind this Trigger is to restrict the user to export the contacts from Zoominfo if number exceeded more than 25 so for that only the test class was written. I just copied the same class and trigger(changed the class and method name) which was written by previous developer for Discover Org and only difference was the number and the lead source.

Not sure, what I should write here and how to even test the test class :( 

Thanks!


 
Shraddha D GuptaShraddha D Gupta
Hi Andrew,
It worked fine while updaitng it to -

System.assert(e.getNumDml() == 26);

Thanks for your help!

Best,
Shraddha