I’m using zend-test in zf3, using doctrine, when I run the test for PostController showAction(), it is showing following error
$ 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
]);
}
Post Service getPost()
public function getPost($postId = null)
{
$post = $this->entityManager->getRepository(Post::class)->find($postId);
return $post;
}
PostControllerTest testIfPostDetailsShownSuccessfully()
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;
}
A post always has one user, I have getUser() method in Post entity which returns User entity object. But I’m unable to mock post object and it always recieving getUser as null.
Any help is much appreciated.