views:

521

answers:

2

I'm trying to stop a method that sends an email from actually sending the email and I think that mock objects (or some variant) are the way to go. Here is the situation:

class UserModel {

    public static function resetPassword()
    {
      // Code to generate new password, etc, etc

      self::_sendMail($to, $body);
      return 1;
    }

    private function _sendMail($to, $body)
    {
      // Send email
    }
}

Is there anyway in PHPUnit that I can mock _sendMail() and inject my own code so I can properly test the other logic in resetPassword() ?

My test would simply look something like:

$this->assertTrue(UserModel::resetPassword());

Thanks for any help.

+2  A: 

I think this is how you'd do it

class MockUserModel extends UserModel
{
    static function _sendMail( $to, $body )
    {
        // do nothing
    }
}

then

$this->assertTrue( MockUserModel::resetPassword() );

But I'm not a unit testing guru, so I apologize if this leads you on a wild goose chase.

Peter Bailey
Of course.. these things are so simple once they're right in front of your face. Thanks a lot Peter.
A: 

You could restructure the original code. It becomes clearer and more testable.

class UserModel
{
    public static function resetPasswordAndSendMail()
    {
      if (!self::resetPassword()) {
        return false;
      }
      self::_sendMail($to, $body);
      return true;
    }

    public static function resetPassword()
    {
      // Code to generate new password, etc, etc
      return true;
    }

    private static function _sendMail($to, $body)
    {
      // Send email
    }
}
GrGr