【问题标题】:Json Assert Fails Laravel 5.5Json 断言失败 Laravel 5.5
【发布时间】:2018-06-03 06:59:47
【问题描述】:

我正在使用 laravel 5.5 制作一个闪存卡应用程序 所以我正在尝试进行第一次测试,但我无法通过。

Failed asserting that an array has the subset Array &0 (
    'data' => Array &1 (
        'id' => 2020
    )
).
--- Expected
+++ Actual
@@ @@
-    [data] => Array
-        (
-            [id] => 2020
-        )
-

/Users/marcosantana/devel/cards/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:290
/Users/marcosantana/devel/cards/tests/Unit/CardTest.php:26

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
测试代码:

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
use App\User;
use App\Card;

class CardTest extends TestCase
{
    use RefreshDatabase;
    use DatabaseMigrations;


    public function testCardsResponds()
    {
        //$user = factory(\App\User::class)->create(['password' => "password"]);
        //$payload = ['email' => $user->email, 'password' => "password"];
        factory(\App\Card::class)->create(['id' => 2020]);//Creates a specific card
        $response = $this->json('GET', 'api/cards');
        $response->assertJson(['data' => ["id" => 2020]]);
/*
        $response
            ->assertStatus(200)
            ->assertSuccessful()
            ->assertJson(['{id}' => 2020]);
            // dd($response);

         */
    }
}

路由/api.php

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('/cards', function(Request $request) {
   return \App\Card::all();
});

服务器输出http://localhost:8000/api/cards

[
  {
    id: 2020,
    tags: "{"lang": "st", "pictures": false}",
    front: "<html><head><title>Optio sit consequuntur vel         excepturi fuga eum amet.</title></head><body><form action="example.net" method="POST"><label for="username">ut</label><input type="text" id="username"><label for="password">excepturi</label><input type="password" id="password"></form><a href="example.org">Sunt ea quia molestias quod consequatur occaecati earum.</a></body></html>
    ",
    back: "<html><head><title>Et qui vel odit qui repellendus nihil architecto.</title></head><body><form action="example.net" method="POST"><label for="username">ratione</label><input type="text" id="username"><label for="password">iste</label><input type="password" id="password"></form><i>Quia dolor voluptas aut et rem natus ut provident sint enim ullam est.</i>Laboriosam voluptas in aut dignissimos accusamus cupiditate molestias vitae.</body></html>
    ",
    created_at: "2017-12-20 10:07:38",
    updated_at: "2017-12-20 10:07:38",
    deleted_at: null
  }
]

所以这似乎是一个明显的解决方案,但我看不出任何帮助都会非常有用。当然这一定很容易,但我真的被淹没了

谢谢!!不要觉得抱歉。你很有帮助。 其实我想扩大一点我的问题。现在我正在尝试验证 json 的其余部分,但是“tags”(mysql json)字段给了我错误 我试试这个:

$response
            ->assertStatus(200)
            ->assertSuccessful()
            ->assertJson([
                [
                    'id' => 2020,
                    'tags' => json_encode(array('lang' => 'mh', 'pictures' => 'false'))
                ]
            ]);

我明白了:

Failed asserting that an array has the subset Array &0 (
    0 => Array &1 (
        'id' => 2020
        'tags' => '{"lang":"mh","pictures":"false"}'
    )
).
--- Expected
+++ Actual
@@ @@
 Array
 (
     [0] => Array
         (
             [id] => 2020
-            [tags] => {"lang":"mh","pictures":"false"}
+            [tags] => {"lang": "mh", "pictures": "false"}

您对此有何看法?再次感谢你! @MarcinNabialek

【问题讨论】:

  • 也许您可以向我们展示您的测试代码?这肯定会有所帮助。
  • 从测试输出中,很明显它期待array('data' =&gt; array('id' =&gt; 2020)),但什么也没得到。
  • @MarcinNabiałek 谢谢我忘记了

标签: laravel laravel-5 phpunit laravel-5.5


【解决方案1】:

代替:

 $response-&gt;seeJsonSubset([["id" =&gt; 2020]]);

我只需要使用:

$response
           /* ->assertStatus(200)
            ->assertSuccessful()*/
            ->assertJson([["id" => 2020]]);

我们得到:

PHPUnit 6.5.4 by Sebastian Bergmann and contributors.

....                                                                4 / 4 (100%)

Time: 900 ms, Memory: 22.00MB

OK (4 tests, 6 assertions)

谢谢你们带领我朝着正确的方向前进。

【讨论】:

    【解决方案2】:

    您的代码有 2 个问题:

    • 您的回复中没有data,您将data 传递给assertJson
    • assertJson 方法需要字符串而不是数组

    在你的情况下,而不是:

     $response->assertJson(['data' => ["id" => 2020]]);
    

    你应该使用:

     $response->seeJsonSubset([["id" => 2020]]);
    

    【讨论】:

    • 感谢您的回复,但它似乎不起作用:BadMethodCallException:方法 seeJsonSubset 不存在。顺便说一句,所有带有 seeJson* 的方法都不起作用,并且在 5.5 文档中它们不使用它们。 @MarcinNabialek
    • @MarcoSantana 对不起。我在我的 Laravel 5.5 中还安装了浏览器套件测试库,并为您提供了来自浏览器套件的方法,而不是纯 Laravel 5.5 安装
    猜你喜欢
    • 2019-01-19
    • 1970-01-01
    • 2020-05-08
    • 2011-05-27
    • 2017-10-23
    • 2021-03-16
    • 2010-09-26
    • 2018-11-09
    相关资源
    最近更新 更多