Mocking Methods Used in Static Methods

I am trying to stop the method that sends an email from actually sending the email, and I think that mock objects (or some options) 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 any way in PHPUnit that I can mock _sendMail () and enter my own code so that I can correctly test other logic in resetPassword ()?

My test will look something like this:

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

Thanks for any help.

+3
source share
3 answers

I think that’s how you would do it.

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

then

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

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

+2
source

. .

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
    }
}
0

It may be useful for you to use an adapter template here . See Docking / Aborting FTP Operations in PHPUnit for a similar scenario and some other possible solutions.

0
source

Source: https://habr.com/ru/post/1704734/


All Articles