PHPUnit 和 ZF2 服务

PHPUnit and ZF2 Services

我在使用 PHPUnit 创建测试时遇到了一个小问题。

这是我的设置:

protected function setUp()
{
    $serviceManager = Bootstrap::getServiceManager();

    $this->mockDriver = $this->getMock('Zend\Db\Adapter\Driver\DriverInterface');
    $this->mockConnection = $this->getMock('Zend\Db\Adapter\Driver\ConnectionInterface');
    $this->mockDriver->expects($this->any())->method('checkEnvironment')->will($this->returnValue(true));
    $this->mockDriver->expects($this->any())->method('getConnection')->will($this->returnValue($this->mockConnection));
    $this->mockPlatform = $this->getMock('Zend\Db\Adapter\Platform\PlatformInterface');
    $this->mockStatement = $this->getMock('Zend\Db\Adapter\Driver\StatementInterface');
    $this->mockDriver->expects($this->any())->method('createStatement')->will($this->returnValue($this->mockStatement));
    $this->adapter = new Adapter($this->mockDriver, $this->mockPlatform);
    $this->sql = new Sql($this->adapter);

    $mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array(), array(), '', false);

    $maiFormuleRevisionTable = $this->getMockBuilder('Maintenance\Model\BDD\PMaiFormulerevisionTable')
        ->setMethods(array())
        ->setConstructorArgs(array($mockTableGateway, $this->adapter, $this->sql))
        ->getMock();
    $maiFormulerevisionService = $this->getMockBuilder('Maintenance\Service\Model\PMaiFormulerevisionService')
        ->setMethods(array())
        ->setConstructorArgs(array($maiFormuleRevisionTable))
        ->getMock();
    $this->assertTrue($maiFormulerevisionService instanceof PMaiFormulerevisionService);

    $this->controller = new RevisionsController($maiFormulerevisionService);

    $this->request    = new Request();
    $this->routeMatch = new RouteMatch(array('controller' => 'index'));
    $this->event      = new MvcEvent();
    $config = $serviceManager->get('Config');
    $routerConfig = isset($config['router']) ? $config['router'] : array();
    $router = HttpRouter::factory($routerConfig);
    $this->event->setRouter($router);
    $this->event->setRouteMatch($this->routeMatch);
    $this->controller->setEvent($this->event);
    $this->controller->setServiceLocator($serviceManager);
}

这是对我的功能的测试:

public function testEditFormuleActionCanBeAccessed()
{
    $this->routeMatch->setParam('action', 'loadformule');
    $this->routeMatch->setParam('idformule', '23');
    $result   = $this->controller->dispatch($this->request);
    $response = $this->controller->getResponse();
    $this->assertEquals(200, $response->getStatusCode());
}

还有我的控制器:

public function loadformuleAction()
{
    try {
        $iStatus = 0;
        $iMaiFormuleRevisionId = (int) $this->params('idformule');

        $oFormule = $this->maiFormulerevisionService->selectByIdOrCreate($iMaiFormuleRevisionId);
        $maiFormulerevisionForm = new PMaiFormulerevisionForm($oFormule);

        if ($this->getRequest()->isPost()) {
            /* etc ... */
        }

        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        $viewModel->setVariables([
            'maiFormulerevisionForm' => $maiFormulerevisionForm,
            'iMaiFormuleRevisionId'  => $oFormule->getMaiFormuleRevisionId(),
            'iStatus'                => $iStatus
        ]);
        return $viewModel;
    } catch (\Exception $e) {
        throw new \Exception($e);
    }
}

但是当我尝试 运行 我的测试时,它显示了一个错误,我指出我的测试没有进入我的服务,当我调用它时 ($this->maiFormulerevisionService) :

1) MaintenanceTest\Controller\RevisionsControllerTest::testEditFormuleActionCanBeAccessed Exception: Argument 1 passed to Maintenance\Form\PMaiFormulerevisionForm::__construct() must be an instance of Maintenance\Model\PMaiFormulerevision, null given

我不明白为什么我的模拟不起作用...

感谢您的回答:)

编辑:

嗯...当我尝试这个时:

$maiFormulerevisionService = new PMaiFormulerevisionService($maiFormuleRevisionTable);

而不是这个:

$maiFormulerevisionService = $this->getMockBuilder('Maintenance\Service\Model\PMaiFormulerevisionService')
            ->setMethods(array())
            ->setConstructorArgs(array($maiFormuleRevisionTable))
            ->getMock();

它进入了服务,但没有进入服务构造函数中指定的 TableGateway ($maiFormuleRevisionTable) ...所以它仍然不起作用...

你设置了一个 mock,但是你还必须在调用方法 selectByIdOrCreate 时设置你的 mock return。既然你这样做了:

$oFormule = $this->maiFormulerevisionService->selectByIdOrCreate($iMaiFormuleRevisionId);
$maiFormulerevisionForm = new PMaiFormulerevisionForm($oFormule);

模拟将为 selectByIdOrCreate 方法 return null,只要您不为此方法设置 return 值。

尝试添加这样的模拟方法:

$mock = $maiFormulerevisionService;
$methodName = 'selectByIdOrCreate';
$stub = $this->returnValue($maiFormuleRevisionTable);

$mock->expects($this->any())->method($methodName)->will($stub);