3

I need to write a unit test on some business logic that happens after the Contact IsEmailBounced field = true. The field is not writeable though. My question is how can I create a test contact with IsEmailBounced = true?

///update I used JSON.deserialize to IsEmailBounced value. But it does not seem to persist when I update the value to pass into the Trigger. When the contact record hits the business logic is showing up as IsEmailBounced = false;

Test method

@IsTest
    static void contactHardBounceTest() {
        Contact c = [
                SELECT Id, IsEmailBounced
                FROM Contact
                LIMIT 1
        ];
        Contact bouncedContact = (Contact) JSON.deserializeStrict(
                '{"IsEmailBounced" : "true"}',
                Contact.class);
        bouncedContact.Id = c.Id;
        System.assertEquals(true, bouncedContact.IsEmailBounced);
        System.debug('bounced contact id ' + bouncedContact.Id);
        System.debug('bounced contact email status ' + bouncedContact.IsEmailBounced);

        update bouncedContact;
        CampaignMember updatedMember = [
                SELECT Id, Status
                FROM CampaignMember
                WHERE ContactId = :bouncedContact.Id
                LIMIT 1
        ];
        System.assertEquals('Bounced', updatedMember.Status, 'Failed assertion on updated member status');
    }

Business logic

public static void updateContacts(List<Contact> newContacts,  Map<Id, Contact> oldContacts){
        List<Contact> unsubContacts = new List<Contact>();
        List<Contact> bouncedContacts = new List<Contact>();
        for(Contact c : newContacts){
            System.debug('Contact Id ' + c.Id);
            System.debug('Email Status in loop ' + c.IsEmailBounced);
            Contact oldContact = oldContacts.get(c.Id);
            if(c.HasOptedOutOfEmail == true && oldContact.HasOptedOutOfEmail == false){
                unsubContacts.add(c);
            }if(c.IsEmailBounced == true){
                bouncedContacts.add(c);
            }
        }
        if(!unsubContacts.isEmpty()){
            updateUnSubCMStatus(unsubContacts);
        }
        if (!bouncedContacts.isEmpty()) {
            updateBouncedCMStatus(bouncedContacts);
        }
    }

1 Answer 1

4

Often when you need to test against fields which are not writeable, serialization provides a good workaround.

Contact record = (Contact)JSON.deserialize(JSON.serialize(new Map<String, Object> {
    'IsEmailBounce' => true
}, Contact.class);
MyService.doSomething(record);
0

You must log in to answer this question.

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