lundi 11 juin 2018

How to test controller action with call of service method in symfony

I want to test if my controller action returns 200 or 404 depends on wether service will find the record or not:

Controller:

/**
 * @Rest\Get("/post/{id}")
 * @param $id
 * @return Response
 */
public function show(?int $id): Response
{
    $post = $this->postService->getPost($id);

    if (empty($post)) {
        throw new HttpException(Response::HTTP_NOT_FOUND, "Post {$id} not found.");
    }

    return new Response($post, Response::HTTP_OK);
}

Service:

public function getPost(int $id): ?Post
{
    return $this->postRepository->find($id);
}

Test:

public function testShowPost()
{
    $client = static::createClient();

    $product = new Post();
    $client->request('GET', '/post/12');

    $postServiceMock = $this->createMock(PostService::class);
    $postServiceMock->expects($this->once())
        ->method('getPost')
        ->willReturn($post);


    $this->assertEquals(200, $client->getResponse()->getStatusCode());
}

Aucun commentaire:

Enregistrer un commentaire