1

我在 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。

任何帮助深表感谢。

4

0 回答 0