PHPUnit如何模拟新创建的模型

时间:2010-08-27 08:13:11

标签: php zend-framework phpunit

我如何坚持为以下代码编写测试。我想模拟$ 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'
        );
    }
}

1 个答案:

答案 0 :(得分:1)

简短的回答:你不能,因为你将依赖项硬编码到方法中。

有三种解决方法:

1)使用的类名可配置,因此您可以执行以下操作:

$className = $this->userModelClassName;
$userModel = new $className();

或2)在方法签名中添加第三个参数,允许传入依赖项

public function isValid($email, $context = NULL, $userModel = NULL)
{
    if($userModel === NULL)
    {
        $userModel = new Application_Model_User();
    }
    // ...
}

或3)按照

中的描述使用set_new_overload()
  

注意: the Test-Helper extension is superseded https://github.com/krakjoe/uopz