Laravel 的 TestCase 方法 seeJson() 只查找数组

2022-08-30 23:43:54

我使用的是Laravel 5.1 Testsuite。

现在,我使用seeJson()方法测试我的json api。此方法需要一个数组,例如:

->seeJson(['created' => 1]);

但是我的 json api 总是返回一个 json 对象或一个包含 json 对象的数组,在这种情况下:

Response::json(['created' => 1], 200);

在上面的例子中,我的json api返回:

{created: 1}

但是 seeJson() 会精确地查找给定的数组:

[created: 1]

我从来没有通过比赛通过我的测试。如何匹配?


答案 1

我收到了类似的错误。

无法在 [{“created”:“1”}......] 中查找 JSON 片段 [“created”:1]

查看源代码,该错误写为:

"Unable to find JSON fragment [{$expected}] within [{$actual}]."

因此,未包含在搜索中[]

Response::json(['created' => 1], 200);

结果:{"created":1}

当我转储方法中的响应内容时,所有值都在引号中。尝试将测试更改为:seeJson()

->seeJson(['created' => '1']);

答案 2

seeJson进行严格的比较,因此:

'created' => 1 (Interpreted as integer)

将失败,因为您的 API 返回的 JSON 实际上是

"created":"1" (interpreted as string)

推荐