【发布时间】:2015-09-26 18:46:44
【问题描述】:
我刚开始在 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,但我显然遗漏了一些东西......
【问题讨论】:
-
它可能会返回 JSON,但错误告诉您的是,当它只接受数组时,您正在将字符串传递给
seeJson()函数。 -
看起来数据已经被格式化为有效的 JSON 格式......在这种情况下,将 JSON 格式化字符串更改为数组的最佳做法是什么?
-
我不熟悉这个功能,但我会写一个答案,希望能更好地解释。
标签: php laravel phpunit laravel-5