Yeni oluşturulan modeli taklit nasıl phpunit

0 Cevap php

Aşağıdaki kodu için bir test yazma ile şaşırıp nasıl. Ben $ userModel alay etmek istiyorum ama nasıl test etmek için bu ekleyebilirsiniz?

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

Update: the Solution

Ben şimdi bağımlılık enjeksiyon kullanır, deneye almak için aşağıdaki benim sınıf değiştirmek yaptım. Bağımlılık enjeksiyon sen van öğrenmek here hakkında daha fazla bilgi

Ben şimdi böyle sınıfını çağırır:

new PC_Validate_UserEmailDoesNotExist(new Application_Model_User()

Refactored sınıfı

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

Birim test

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'
        );
    }
}

0 Cevap