首页 > 解决方案 > 如何对这个 try catch 进行单元测试

问题描述

我正在尝试 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() 的代码覆盖率。

代码覆盖率

如您所见,我不测试 catch 案例。我该怎么做 ?我已经尝试模拟 404 HTTP 响应捕获某些东西,但它不起作用。你知道我该怎么做吗?

谢谢。

编辑:我为 catch 案例尝试了这个 ->

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 匹配失败。看来我的模拟客户端无法正常工作。

标签: phpphpunittry-catchcode-coverage

解决方案


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

也许尝试模拟客户端,以及何时触发抛出异常?

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


推荐阅读