gpt4 book ai didi

PHPUnit 模拟 View 助手 ZF2

转载 作者:可可西里 更新时间:2023-11-01 00:42:05 25 4
gpt4 key购买 nike

我创建了一个 View 助手:

class SousMenuContrat extends AbstractHelper
{
private $maiContratService;

public function __construct(
FMaiContratService $maiContratService,
) {
$this->maiContratService = $maiContratService;
}

public function __invoke($iMaiContratId, $sActive)
{
$oContrat = $this->maiContratService->selectById($iMaiContratId);

return $this->getView()->partial('maintenance/sousmenucontrat', array(
'oContrat' => $oContrat
));
}
}

所以现在我需要用 PHPUnit 来测试它:

class SousMenuContratTest extends TestCase
{
private $myService;

public function setUp()
{
$maiContratService = $this->getMockBuilder('Maintenance\Service\Model\FMaiContratService')
->disableOriginalConstructor()
->getMock();

$oContrat = new FMaiContrat();
$stub = $this->returnValue($oContrat);
$maiContratService->expects($this->any())->method('selectById')->will($stub);
$this->myService = new SousMenuContrat(
$maiContratService
);
}

public function testInvoque()
{
$this->myService->__invoke(2, 'contrat');
}
}

但是测试发送错误,因为测试不知道:

$this->getView()->partial();

提前致谢:)

最佳答案

在您的测试中,您需要模拟 getView() 返回的渲染器:

    /** @var PhpRenderer|\PHPUnit_Framework_MockObject_MockObject $rendererMock */
$rendererMock = $this->getMockBuilder('Zend\View\Renderer\PhpRenderer')
->disableOriginalConstructor()
->getMock();
$rendererMock->expects($this->once())
->method("partial")
->with(array(
'maintenance/sousmenucontrat',
array('oContrat' => new FMaiContrat()),
));
$this->myService->setView($rendererMock);

最好的解决方案是在 with() 中使用您在 setUp() 中实例化的相同 FMaiContrat 对象,但在这种情况下,这也适用。

编辑:完整的测试代码如下所示:

class SousMenuContratTest extends TestCase
{
private $myService;

public function setUp()
{
$maiContratService = $this->getMockBuilder('Maintenance\Service\Model\FMaiContratService')
->disableOriginalConstructor()
->getMock();

$oContrat = new FMaiContrat();
$stub = $this->returnValue($oContrat);
$maiContratService->expects($this->any())->method('selectById')->will($stub);
$this->myService = new SousMenuContrat(
$maiContratService
);
}

public function testInvoque()
{
/** @var PhpRenderer|\PHPUnit_Framework_MockObject_MockObject $rendererMock */
$rendererMock = $this->getMockBuilder('Zend\View\Renderer\PhpRenderer')
->disableOriginalConstructor()
->getMock();
$rendererMock->expects($this->once())
->method("partial")
->with(array(
'maintenance/sousmenucontrat',
array('oContrat' => new FMaiContrat()),
));
$this->myService->setView($rendererMock);
$this->myService->__invoke(2, 'contrat');
}
}

关于PHPUnit 模拟 View 助手 ZF2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32902200/

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