【问题标题】:Type Error exception while unit testing (zend-test, PHPUnit)单元测试时类型错误异常(zend-test,PHPUnit)
【发布时间】:2019-05-31 17:13:14
【问题描述】:

我正在尝试在 Zend FrameWork 中测试一个简单的控制器操作,但我不能 100% 确定为什么我的模拟不起作用。

原作:

 public function overviewAction()
    {
        $page = $this->params()->fromQuery('page', 1);
        $count = 10;

        $user = $this->authenticationService->getIdentity();

        return new ViewModel([
            'paginator' => $this->agentService->getAgentsOwnedByUser($page, $count, $user),
        ]);
    }

我对此操作的测试

    /**
     * Set Rbac Role and route
     */
    $url = "cp/agent";
    $this->setRbacGuards(['admin']);
    //Nb Rbac class code is here

    /**
     * Objects required in this test
     */
    $user = $this->createMock(User::class);
    $paginator = $this->createMock(Paginator::class);

    /**
     * Mock classes and their methods to be called
     */
    $authentication = $this->createMock(AuthenticationService::class);
    $authentication
        ->expects($this->once())
        ->method('getIdentity')
        ->will($this->returnValue($this->registerMockObject($user)));


    $agentService = $this->createMock(AgentService::class);
    $agentService
        ->expects($this->once())
        ->method('getAgentsOwnedByUser')
        ->will($this->returnValue($this->registerMockObject($paginator)));

    $this->dispatch('/'.$url);
    $this->assertResponseStatusCode(200);

错误信息

 There was 1 failure:

    1) ControlPanelTest\Controller\AgentControllerTest::testAgentOverviewActionCanBeAccessed
    Failed asserting response code "200", actual status code is "500"

    Exceptions raised:
    Exception 'TypeError' with message 'Argument 3 passed to 

    Admin\Service\AgentService::getAgentsOwnedByUser() must be an instance of Domain\User\User, null given
.

为了完整性,Rbac 类

public function rbacGuards($roles)
    {
        /**
         * Deal with Rbac Guards
         */
        $roleService = $this->getApplicationServiceLocator()->get(RoleService::class);
        $identityProvider = $this->prophesize(IdentityProviderInterface::class);
        $identity = $this->prophesize(IdentityInterface::class);
        // Here you use the setter to inject your mocked identity provider
        $roleService->setIdentityProvider($identityProvider->reveal());
        $identityProvider->getIdentity()->shouldBeCalled()->willReturn($identity->reveal());
        $identity->getRoles()->shouldBeCalled()->willReturn($roles);
    }

预后

似乎没有调用模拟...

【问题讨论】:

    标签: zend-framework2 phpunit zend-test


    【解决方案1】:

    在您的示例中,您创建了 $authentication 模拟,但您没有将其注册为您正在测试的类的属性。 因此,当overviewAction 使用$this->authenticationService->getIdentity(); 时,它不是使用您创建的模拟。

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2012-11-18
    • 2013-09-22
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 2011-06-06
    • 1970-01-01
    相关资源
    最近更新 更多