Version 4 supported
This version of Silverstripe CMS is still supported though will not receive any additional features. Go to documentation for the most recent stable version.

Testing email within unit tests

Silverstripe CMS's test system has built-in support for testing emails sent using the Email class. If you are running a SapphireTest test, then it holds off actually sending the email, and instead lets you assert that an email was sent using this method.

use SilverStripe\Control\Email\Email;

public function MyMethod()
    $e = new Email();
    $e->To = '';
    $e->Subject = 'Hi there';
    $e->Body = 'I just really wanted to email you and say hi.';

To test that MyMethod sends the correct email, use the SapphireTest::assertEmailSent() method.

$this->assertEmailSent($to, $from, $subject, $body);

// to assert that the email is sent to the correct person
$this->assertEmailSent('', null, '/th.*e$/');

Each of the arguments ($to, $from, $subject and $body) can be either one of the following.

  • A string: match exactly that string
  • null/false: match anything
  • A PERL regular expression (starting with '/')

Related documentation

API documentation