gpt4 book ai didi

php - 在函数中模拟 Propel 查询 (Symfony2)

转载 作者:行者123 更新时间:2023-12-02 04:39:10 25 4
gpt4 key购买 nike

我正在尝试为使用 Propel 查询的类编写单元测试(使用 phpunitmockery)。
我如何模拟查询 $contact = ClientContactQuery::create()->findPK($id);

我正在努力寻找这方面的例子。

我的类(class);

<?php
namespace MyBundle\Classes;

use MyBundle\Model\ClientContactQuery;
use MyBundle\Model\ClientContact;

class Contacts {

protected $_cache;

public function __construct($cache)
{
$this->_cache = $cache;
}

public function getContact($id)
{
$contact = ClientContactQuery::create()->findPK($id);

if (! $contact) {
throw new NotFoundHttpException('Client contact not found.');
}

return $contact;
}

}

到目前为止我的测试用例;

<?php
namespace MyBundle\Tests\Classes;

use Mockery as m;
use MyBundle\Classes\Contacts as c;

class ContactsTest extends \PHPUnit_Framework_TestCase
{
public function tearDown()
{
m::close();
}

public function testGetValidContact()
{
// Arrange
$cache = m::mock('cache');

// Act
$contact = new c($cache);
// am lost at this point :-(

// Assert
$this->assertInstanceOf('MyBundle\Classes\Contacts', $contact);
}

}

最佳答案

静态函数不适合单元测试,请不要创建私有(private)方法并对其进行模拟。

我强烈建议创建一个查询工厂。这不仅会让您能够注入(inject)和单元测试您的代码,而且如果您将来想使用 XYZ orm 而不是 Propel,它会让生活变得更轻松。

#

<?php
namespace MyBundle\Classes;

use MyBundle\Model\ClientContactQuery;
use MyBundle\Model\ClientContact;

class Contacts {

protected $_cache;

/** @var QueryFactory */
private $queryFactory;


public function __construct( $cache, QueryFactory $queryFactory ) {
$this->_cache = $cache;
$this->queryFactory = $queryFactory;
}

public function getContact( $id ) {
$contact = $this->queryFactory->newClientContactQuery()->findPK($id);

if (! $contact) {
throw new NotFoundHttpException('Client contact not found.');
}

return $contact;
}

}

#

<?php
class QueryFactory {

const CLASS_NAME = __CLASS__;

public function newClientContactQuery() {
return ClientContactQuery::create();
}

public function newSomeOtherQuery() {
return SomeOtherQuery::create();
}

}

#

<?php
namespace MyBundle\Tests\Classes;

use Mockery as m;
use MyBundle\Classes\Contacts as c;

class ContactsTest extends \PHPUnit_Framework_TestCase {
public function tearDown() {
m::close();
}

public function testGetValidContact() {
$cache = m::mock( 'cache' );
$queryFactory = m::mock( QueryFactory::CLASS_NAME );
$clientContactQuery = m::mock( 'ClientContanctQuery' );

$contact = new c($cache, $queryFactory);

$queryFactory->shouldReceive('newClientContactQuery')->with()->once()->andReturn( $clientContactQuery );
$clientContactQuery->shouldReceive('findPK')->with('myTestInputId')->once->andReturn('something?');

$this->assertInstanceOf('MyBundle\Classes\Contacts', $contact);
}

}

关于php - 在函数中模拟 Propel 查询 (Symfony2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21304842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com