我是如何为下面的代码编写测试的。我想模拟$userModel,但如何将其添加到测试中?
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;
}
}
}
我确实将我的类更改为以下内容以使其可测试,它现在使用依赖注入。有关依赖注入的更多信息,请参阅
here
我现在这样称呼这个班:
new PC_Validate_UserEmailDoesNotExist(new Application_Model_User()
重构类
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;
}
}
}
单元测试
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('jef@test.com', 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('jef@test.com', NULL),
'The email should exist'
);
}
}