Unit Testing Salesforce Bounced Email Addresses in Apex

Recently my team at work ran into a bug in an Apex class around trying to send email to a bounced email address. Simulating that for an Apex test requires setting two specific fields.

Recently my team at work ran into a bug in an Apex class around trying to send email to a bounced email address. When going to write a unit test to confirm the behavior, we ran into a problem: the Contact object has a boolean IsEmailBounced field, but it has no setter. How can we simulate a bounced email in a unit test when we can't set the field?

We found the answer on the Trailblazer Community site.

Turns out IsEmailBounced is a computed field based on EmailBouncedDate and EmailBouncedReason. Setting those fields in the unit test allowed us to test and fix the bug.

Here's the documentation on the Contact object, including the IsEmailBounced, EmailBouncedDate, and EmailBouncedReason fields.