php - 如何对这个 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 匹配失败。看来我的模拟客户端无法正常工作。
解决方案
我知道,这是一个旧帖子,但是..
也许尝试模拟客户端,以及何时触发抛出异常?
因此,当您抛出 ClientException 时,您应该检查 TwitterResponse 结果。当你抛出 DummyException 时,你应该期待 DummyException。
推荐阅读
- python - 警告:无法从 javaldx 读取路径
- multer - 在节点中使用 multer 上传文件时文件大小显示不正确
- python - 如何解决 TensorFlow 中的“BiasGrad 需要张量大小 <= int32 max”InvalidArgumentError?
- php - 为什么 Laravel 6.x 默认创建 failed_jobs 迁移
- css - 何时使用 rel="preload"?为什么预加载字体/FontAwesome 是个好主意?
- pine-script - Pine Script,series[0] 类型不是整数?
- google-analytics - Google Analytics、AMP 和跟踪代码管理器、动态客户端计算指标
- javascript - 如何在javascript中使用从Django传递的上下文变量?已经改成Json类型
- selenium - 无法导入 CucumberOptions 和 Cucumber
- android - 如何从具有不同条件的同一张表中获取行