phpunit使用zend Framework 3和原则,模拟无法正常工作

时间:2019-02-08 13:55:37

标签: php zend-framework doctrine phpunit zend-test

我在zf3中使用zend-test,使用了学说,当我为PostController showAction()运行测试时,它显示以下错误

$ vendor/bin/phpunit --testsuite Post --stderr
PHPUnit 7.5.2 by Sebastian Bergmann and contributors.

F      1 / 1 (100%)

Time: 169 ms, Memory: 16.00MB

There was 1 failure:

1) PostTest\Controller\PostControllerTest::testIfPostDetailsShownSuccessfully
Failed asserting response code "200", actual status code is "500"

Exceptions raised:
Exception 'TypeError' with message 'Return value of Post\Entity\Post::getUser() must be an instance of User\Entity\User, null returned' in /var/www/html/crud/module/Post/src/Entity/Post.php:122

/var/www/html/crud/vendor/zendframework/zend-test/src/PHPUnit/Controller/AbstractControllerTestCase.php:451
/var/www/html/crud/module/Post/test/Controller/PostControllerTest.php:95

PostController showAction()

public function showAction()
{
    $postId = $this->params()->fromRoute('postId');
    $post = $this->postService->getPost($postId);

    return new ViewModel([
        'post' => $post
    ]);
} 

邮政服务getPost()

public function getPost($postId = null)
{
    $post = $this->entityManager->getRepository(Post::class)->find($postId);

    return $post;
}

PostControllerTest testIfPostDetailsS​​hownSuccessfully()

public function testIfPostDetailsShownSuccessfully()
{

            $mockedEm = $this->createMock(EntityManager::class);

            $postRepositoryMock = $this->createMock(PostRepository::class);
            $postRepositoryMock->expects($this->any())
                ->method('find')
                ->willReturn($this->getPostMock());

            $postRepositoryMock->expects($this->any())
                ->method('findOneBy')
                ->willReturn($this->getPostMock());

            $userRepositoryMock = $this->createMock(UserRepository::class);
            $userRepositoryMock->expects($this->any())
                ->method('find')
                ->willReturn(new User());

            $userRepositoryMock->expects($this->any())
                ->method('findOneBy')
                ->willReturn(new User());

            $userEntityMock = $this->createMock(UserRepository::class);
            $userEntityMock->expects($this->any())
                ->method('find')
                ->willReturn(new User());

            $this->dispatch('/post/1');
            $this->assertResponseStatusCode(200);
  }

/**
 * @return MockObject
 */
public function getPostMock()
{
    $user = new User();
    $user->setEmail('a@a.in');

    $postMock = $this->createMock(Post::class);
    $postMock->expects($this->any())
        ->method('getUser')
        ->willReturn($user);

    return $postMock;
}

帖子始终有一个用户,我在Post实体中有getUser()方法,该方法返回User实体对象。但是我无法模拟post对象,它总是将getUser接收为null。

非常感谢您的帮助。

0 个答案:

没有答案