如何单独测试这个尝试catch

时间:2018-05-18 18:47:52

标签: php phpunit try-catch code-coverage

我正在尝试100%代码覆盖我的服务。这是一种方法:

<?php

 * Search to public accounts.
 *
 * @param string $query
 *
 * @return TwitterResponse
 */
public function search(string $query): TwitterResponse
{
    try {
        $response = $this->client->getClient()->get(UserEnum::URI_SEARCH, [
            'query' => ['q' => $query,]
        ]);
    } catch (ClientException $e) {
        $response = $e->getResponse();
    }

    return new TwitterResponse($response);
}

它只是使用Twitter API获取用户。

在我看来,我应该开发两个测试:一个用于尝试,一个用于捕获。贝娄是我尝试的考验。

<?php

/**
 * @return void
 */
public function setUp(): void
{
    $this->prophet = new Prophet();

    $this->client = $this->prophet->prophesize(Client::class);
    $this->client->get(Argument::any(), Argument::any())->willReturn(new TwitterResponse(new Response()));
    $this->client->post(Argument::any(), Argument::any())->willReturn(new TwitterResponse(new Response()));

    $this->twitterClient = $this->prophet->prophesize(TwitterClient::class);
    $this->twitterClient->getClient()->willReturn($this->client);

    $this->userService = new UserService($this->twitterClient->reveal());
}

/**
 * Tests if a TwitterResponse is returned with status HTTP_OK.
 *
 * @return void
 */
public function testGetOk(): void
{
    $actual = $this->userService->get('');

    $this->assertEquals(get_class($actual), TwitterResponse::class);
    $this->assertEquals(HttpResponse::HTTP_OK, $actual->getStatusCode());
}

了解get()的代码覆盖率。

Code coverage

正如您所看到的,我不测试捕获案例。我该怎么做 ?我已经尝试模拟404 HTTP响应捕获一些东西,但它没有用。你知道我怎么做吗?

感谢。

编辑:我尝试了这个案例 - &gt;

public function testGetKo(): void
{
    $response = new TwitterResponse(new Response(HttpResponse::HTTP_NOT_FOUND));
    $response->setStatusCode(HttpResponse::HTTP_NOT_FOUND);
    $this->client = $this->prophet->prophesize(Client::class);
    $this->client->get(Argument::any(), Argument::any())->willReturn($response);
    $this->twitterClient = $this->prophet->prophesize(TwitterClient::class);

    $actual = $this->userService->get('');

    $this->assertEquals(get_class($actual), TwitterResponse::class);
    $this->assertEquals(HttpResponse::HTTP_NOT_FOUND, $actual->getStatusCode());
}

Phpunit返回:声明200个匹配的预期404失败。我的模拟客户端似乎运行不正常。

2 个答案:

答案 0 :(得分:1)

我知道,这是一个旧帖子,但是..

也许尝试模拟客户端,当它触发时抛出异常?

因此,当您抛出 ClientException 时,您应该检查 TwitterResponse 结果。当你抛出 DummyException 时,你应该期待 DummyException。

答案 1 :(得分:0)

这是未经测试的,因为我通常不会使用预言,但我会与其他模拟框架类似:

public function testGetKo(): void
{
    // ... other setup

    $exception = new ClientException();
    $this->client = $this->prophet->prophesize(Client::class);
    $this->client->get(Argument::any(), Argument::any())->willThrow($exception);

在运行正在测试的函数之前,您可能会添加$this->expectException(ClientException::class);