Laravel TDD无法断言数组具有键'id'

问题描述 投票:1回答:1

我一直在跟踪series以赶上Laravel的TDD。我得到

未能断言数组具有键'id'。

运行测试命令时的错误消息。

下面是我的代码:

api.php

Route::namespace('API')->group(function(){
    Route::post('/products', 'ProductController@store');
});

ProductController.php

namespace App\Http\Controllers\API;
use App\Product;
public function store(Request $request)
    {
       $product =  Product::create([
            'name' => $request->name,
            'slug' => $request->slug,
            'price' => $request->price
        ]);
        return response()->json($product, 201);
    }

ProductControllerTest.php

public function can_create_a_product()
    {
        $faker = Factory::create();

        $response = $this->json('POST', '/api/products', [
            'name' => $name = $faker->company,
            'slug' => str_slug($name),
            'price' => $price = random_int(10, 100)
        ]);
        $response->assertJsonStructure([
            'id', 'name', 'slug', 'price', 'created_at'
        ])
        ->assertJson([
            'name' => $name,
            'slug' => str_slug($name),
            'price' => $price
        ])
        ->assertStatus(201);

        $this->assertDatabaseHas('products', [
            'name' => $name,
            'slug' => str_slug($name),
            'price' => $price
        ]);
        
    }

产品结构表:

id | image | name | price

我关注的视频系列是在laravel 5.7上制作的,我正在运行Laravel 7。这是错误的原因吗?

php laravel tdd phpunit-testing laravel-7
1个回答
0
投票

发现我需要使用

use RefreshDatabase;

特征。

© www.soinside.com 2019 - 2024. All rights reserved.