2

I have an .addError() on a trigger on Account and can't seem to write test coverage for it. I have both insert and update scenarios (i just listed the insert):

if (Trigger.isInsert) {
            Set<String> userGroup = new Set<String>();
            Id userId = UserInfo.getUserId(); //00534000009QnEtAAK
            system.debug('userId:: ' + userId);
            List<GroupMember> groupName = [select group.name, group.DeveloperName from GroupMember where UserOrGroupId = :userId];
            for (GroupMember g : groupName) {
                userGroup.add(g.group.name);
            }
            system.debug('userGroup:: ' + userGroup);
            if (userGroup.contains('Auto Data Standardization') && a.Fed_Tax_ID__c != '' && a.Fed_Tax_ID__c != null) {
                federalTaxId = a.Fed_Tax_ID__c.replaceALl('[^0-9]', '');
                if (federalTaxId.length() > 9) {
                    federalTaxId = '';
                    system.debug('a.Fed_Tax_ID__c4: ' + a.Fed_Tax_ID__c);
                } else if (federalTaxId.length() < 9) {
                    federalTaxId = '';
                    system.debug('a.Fed_Tax_ID__c5: ' + a.Fed_Tax_ID__c);
                }
                a.Fed_Tax_ID__c = federalTaxId;
            }
            else if (a.Fed_Tax_ID__c != '' && a.Fed_Tax_ID__c != null) {
                federalTaxId = a.Fed_Tax_ID__c.replaceALl('[^0-9]', '');
                if (federalTaxId.length() > 9) {
                    a.Fed_Tax_ID__c = '';
                    String error_msg = 'The entered Federal Tax Id number is incorrect. Please ensure the following formatting is followed: ##-####### or ######### and that there are 9 numeric digits.';
                    a.addError(error_msg);
                } else if (federalTaxId.length() < 9) {
                    a.Fed_Tax_ID__c = '';
                    String error_msg = 'The entered Federal Tax Id number is incorrect. Please ensure the following formatting is followed: ##-####### or ######### and that there are 9 numeric digits.';
                    a.addError(error_msg);
                }
                a.Fed_Tax_ID__c = federalTaxId;

                system.debug('hash debug2: ' + a.Fed_Tax_ID__c);
            }
            if(a.Fed_Tax_ID__c != '' && a.Fed_Tax_ID__c != null){
                String b = a.Fed_Tax_ID__c.replaceAll('[^0-9]', '');
                String temp = b.replace('-', '') + '3M!NamoN#piM'; // remove dashes and salts are added to the end of the string
                Blob mac = Crypto.generateDigest('SHA-256', Blob.valueOf(temp)); // you should be generating a digest, not a message authenticator
                String csvBody = EncodingUtil.convertToHex(mac);
                system.debug('hash csvBody3:: ' + csvBody);
                a.Fed_Tax_ID_Hashed__c = csvBody;
            }
        }

I have tried writing a try catch on it with throwing an exception but this doesn't seem to work either. Any help?

static testmethod void insertAccountError(){
    try {
        Account l = new Account(Name = 'test', Fed_Tax_ID__c = '754');
        insert l;
        throw new MyException('The entered Federal Tax Id number is incorrect. Please ensure the following formatting is followed: ##-####### or ######### and that there are 9 numeric digits');
    }
    catch(Exception e){
        Boolean expectedExceptionThrown =  e.getMessage().contains('The entered Federal Tax Id number is incorrect. Please ensure the following formatting is followed: ##-####### or ######### and that there are 9 numeric digits') ? true : false;
        System.AssertEquals(expectedExceptionThrown, true);
    }
}

static testmethod void updateAccountError(){
    try {
        Account a = new Account(Name = 'TestAccount');
        insert a;
        Account a2 = new Account(Id = a.Id, Name = 'test', Fed_Tax_ID__c = '75-1234567777');
        update a2;
        throw new exception('The entered Federal Tax Id number is incorrect. Please ensure the following formatting is followed: ##-####### or ######### and that there are 9 numeric digits');
    }
    catch(Exception e){
        Boolean expectedExceptionThrown =  e.getMessage().contains('The entered Federal Tax Id number is incorrect. Please ensure the following formatting is followed: ##-####### or ######### and that there are 9 numeric digits') ? true : false;
        System.AssertEquals(expectedExceptionThrown, true);
    }
}
2
  • And where do you get federalTaxId? You need to set up your test data such that its length is less than 9.
    – Adrian Larson
    Oct 31, 2017 at 22:31
  • sorry I have both scenarios, when the tax id is longer then 9 or less then 9. either way it is not handling properly. I will update full code.
    – Olivia
    Oct 31, 2017 at 22:33

1 Answer 1

6

Generally speaking, you need to set up your data such that you enter that execution block. Note that once you do, your DML Statement is going to throw a DmlException. Here's how I would generally catch those:

// set up data to enter correct block

DmlException expectedException;
Test.startTest();
    try
    {
        // perform operation
    }
    catch (DmlException dmx)
    {
        expectedException = dmx;
    }
Test.stopTest();

system.assertNotEquals(null, expectedException, 'Informative message here');
// optionally query for data to further verify operation failed

Note that when your trigger logic touches on logic around the running user, you should run as a specific user in your test:

User runningUser = new User(/*required fields*/);
insert runningUser;

Group filterGroup = new Group(Name='Auto Data Standardization Testing...');
insert filterGroup;

insert new GroupMember(GroupId=filterGroup.Id, UserOrGroupId=runningUser.Id);

system.runAs(runningUser)
{
    // do stuff
}
1
  • thank you all worked and great suggestions. I've never worked with addError() before and this is a great way to handle it. I will update with my additions!
    – Olivia
    Nov 1, 2017 at 2:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .