PHPUnit how to mock newly created model

cian1500ww

New Member
How I'm stuck with writing a test for the following code. I want to mock the $userModel but how can I add this to the test?\[code\]class PC_Validate_UserEmailDoesNotExist extends Zend_Validate_Abstract{ public function isValid($email, $context = NULL) { $userModel = new Application_Model_User(); $user = $userModel->findByEmailReseller($email, $context['reseller']); if ($user == NULL) { return TRUE; } else { return FALSE; } }}\[/code\]Update: the SolutionI did change my class to the following to get it testable, it now uses dependency injection. More information about dependency injection you van find out hereI now call the class like this:\[code\]new PC_Validate_UserEmailDoesNotExist(new Application_Model_User()\[/code\]The refactored class\[code\]class PC_Validate_UserEmailDoesNotExist extends Zend_Validate_Abstract{ protected $_userModel; public function __construct($model) { $this->_userModel = $model; } public function isValid($email, $context = NULL) { if ($this->_userModel->findByEmailReseller($email, $context['reseller']) == NULL) { return TRUE; } else { return FALSE; } }}\[/code\]The unit test\[code\]class PC_Validate_UserEmailDoesNotExistTest extends BaseControllerTestCase{ protected $_userModelMock; public function setUp() { parent::setUp(); $this->_userModelMock = $this->getMock('Application_Model_User', array('findByEmailReseller')); } public function testIsValid() { $this->_userModelMock->expects($this->once()) ->method('findByEmailReseller') ->will($this->returnValue(NULL)); $validate = new PC_Validate_UserEmailDoesNotExist($this->_userModelMock); $this->assertTrue( $validate->isValid('[email protected]', NULL), 'The email shouldn\'t exist' ); } public function testIsNotValid() { $userStub = new \Entities\User(); $this->_userModelMock->expects($this->once()) ->method('findByEmailReseller') ->will($this->returnValue($userStub)); $validate = new PC_Validate_UserEmailDoesNotExist($this->_userModelMock); $this->assertFalse( $validate->isValid('[email protected]', NULL), 'The email should exist' ); }}\[/code\]
 
Back
Top