Skip to main content
Tweeted twitter.com/StackSalesforce/status/794899152190705665
edited tags
Link
Adrian Larson
  • 151.4k
  • 38
  • 247
  • 431
Source Link
Aidan
  • 14k
  • 1
  • 41
  • 86

Changing username in Apex Test is emailing the user

I'm testing a controller for a Customer Community page where users can change their email address. To keep things simple for the user, I'm getting the controller to also change their username to match the email address.

When I ran my tests, I received an email saying that my username had changed. So, I boiled it down to a simple test case:

@istest
public class UsernameChangeTest {
    @isTest static void changeUserName() {
        update new User(Id = UserInfo.getUserId(), Username = 'not+' + UserInfo.getUserEmail());
    }
}

If I run that as a test, I get an email saying that my username has changed. The username hasn't really changed - I guess it's been rolled back like test data always is.

So it looks like a bug in SF's sandboxing of tests? Anyone come across this before? Any workarounds? (other than horrible Test.isRunningTest() hacks to avoid certain lines of code)