php - Zend Framework 2 中使用 PHPUnit 模拟服务

标签 php unit-testing zend-framework2 phpunit

我正在尝试模拟删除操作。删除方法位于服务内部,因此我想模拟 Controller 内部请求的服务。

这是删除操作:

public function deleteAction()
{
    try {
        $internId = $this->params()->fromRoute('id', 0);
        $this->getServiceLocator()->get('internService')->removeIntern($internId);
    } catch (Exception $e) {
        $this->flashMessenger()->addErrorMessage($e->getMessage() . '<br>' . $e->getTraceAsString());
    }
    return $this->redirect()->toRoute('intern/list');
}

这是执行的服务操作:

 public function removeIntern($internId)
{
    try {
        $intern = $this->getIntern($internId);
        $this->removeEntity($intern);
        $this->flashMessenger()->addSuccessMessage("Intern has Successfully been Removed");
    } catch (Exception $e) {

    }
}

我想在我的测试中模拟这个方法。

我已经尝试过这个:

 public function testDeleteAction()
{
    $this->mockBjy();
    $this->mockZFC();

   $internMock = $this->getMockBuilder('Intern\Service\internService')
                        ->disableOriginalConstructor()
                        ->getMock();

$internMock->expects($this->any())
                ->method('removeIntern')
                ->will($this->returnValue(null));

$serviceManager = $this->getApplicationServiceLocator();
$serviceManager->setAllowOverride(true);
$serviceManager->setService('Intern\Service\internService', $internMock);

    $this->dispatch('/intern/delete/86');
    $this->assertModuleName('intern');
    $this->assertControllerName('intern\controller\intern');
    $this->assertControllerClass('InternController');
    $this->assertActionName('delete');
    $this->assertMatchedRouteName('intern/delete');
}

运行 PHPUnit 命令时,我在控制台中收到错误:

EntityManager#Remove() expects parameter 1 to be an entity object, NULL given.

如有任何帮助,我们将不胜感激,提前致谢。

最佳答案

看来您没有在服务管理器中正确设置模拟。您将在操作中通过 internService 获取服务。在您的测试中,您将模拟放置在 Intern\Service\internService 中。

所以发生的事情是您正在使用真正的服务而不是您的模拟服务。将您的 setService 调用更改为:

$serviceManager->setService('internService', $internMock);

关于php - Zend Framework 2 中使用 PHPUnit 模拟服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30214859/

相关文章:

php - 在 php 中用 ' 替换每个 '

java - 不要在 uni-test 中启动 spring 上下文

c++ - visual studio 是否有任何扩展来优化 C++ 代码单元测试?

php - mysql 查询是否接受换行符转义?

php - 从 php 中的数组构建 "crosstab"或 "pivot"表

python - 如何使用不同版本的 Python 运行 Python Nose 测试

mongodb - Doctrine2 MongoDB ODM 复合键(UniqueEntity)

doctrine-orm - ZF2主义 : When to flush ObjectManager

php - ZF2 - 在 Controller 中获取当前 URL

php - 每10分钟从MySql表中获取数据