gpt4 book ai didi

php - Laravel 5.1 PHPUnit 使用 JSON 测试 API

转载 作者:行者123 更新时间:2023-12-02 15:32:27 24 4
gpt4 key购买 nike

我刚刚开始在 Laravel 5.1 中使用单元测试来测试我正在构建的 API,并且我可以让 PHPUnit 与 ExampleTest.php 一起正常工作,但是当我创建自己的测试时,它每次都会失败。

这是我的 API 端点 v1/conversations 的响应:

{
"data": [
{
"id": 1,
"created_at": "2015-07-05",
"updated_at": "2015-07-07"
},
{
"id": 2,
"created_at": "2015-07-06",
"updated_at": "2015-07-08"
}
]
}

这是我的 ConversationsTest.php:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ConversationsTest extends TestCase
{

public function test_list_conversations()
{
$this->get('v1/conversations')->seeJson('data');
}
}

但是当我运行测试时,我得到以下结果:

There was 1 error:

1) ConversationsTest::test_list_conversations
ErrorException: Argument 1 passed to Illuminate\Foundation\Testing\TestCase::seeJson() must be of the type array, string given

我的 API 没有返回有效的 JSON 数据吗?为什么 Laravel 的 seeJson 方法无法解释响应?我尝试遵循 Laravel 5.1 Testing APIs documentation ,但我显然错过了一些东西......

最佳答案

您的端点返回的数据正常,不应修改。该错误只是告诉您正在将字符串传递到函数 seeJson('data');

根据这里,https://github.com/laracasts/Integrated/wiki/Testing-APIs ,您应该能够像这样使用它来验证是否返回了一些 JSON...

$this->get('v1/conversations')->seeJson();

你还可以向这个函数传入一个数组来查看某部分数据是否存在...

$this->get('v1/conversations')->seeJson([
'data' => 'some data',
]);

不过,除非您传入端点也返回的整个数组,否则这可能会失败。

唯一不能做的就是将字符串传递给此函数,因为它不知道如何处理字符串。

关于php - Laravel 5.1 PHPUnit 使用 JSON 测试 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31299764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com