如何修复api json删除请求

时间:2019-03-25 06:07:22

标签: json laravel unit-testing

在下面的代码中,我试图创建一个新类别(名称=“待删除”),然后将其删除。

第一部分代码运行良好,每次运行单元测试时,我都可以在数据库中看到新记录

但是我在重新编码删除方面遇到问题。我的代码有什么问题

public function testCategoryDeletion()
{
    $user = \App\User::find(1);
    //dd($user->name);
    $category = \App\Category::create(['name' => 'To be deleted']);
    //dd($category->id);
    $response = $this->actingAs($user, 'api')
        ->json('DELETE', "/api/category/{$category->id}")
        ->assertStatus(200)->assertJson([
            'status'  => true,
            'message' => 'Category Deleted',
        ]);
}

测试用例输出

PS C:\xampp\htdocs\Chathura\Vue_Laravel_API> ./vendor/bin/phpunit
PHPUnit 7.5.7 by Sebastian Bergmann and contributors.

.    .    .    .    .    .    .                                                             7 / 7 (100%)

Time: 1.53 minutes, Memory: 18.00 MB

OK (7 tests, 65 assertions)
PS C:\xampp\htdocs\Chathura\Vue_Laravel_API>

在数据库中,已创建但未删除重新编码,

database

1 个答案:

答案 0 :(得分:0)

我按照以下步骤修复了控制器,现在它可以正常工作了,

public function destroy(Category $category)
{

    $status  = $category->delete();

    return response()->json([
        'status' => $status,
        'message' => $status ? 'Category Deleted' : 'Error Deleting Category'
    ]);

}

API路由

Route::group(['middleware' => 'auth:api'], function(){
        Route::resource('/task', 'TaskController');
        Route::resource('/category', 'CategoryController');
        Route::get('/category/{category}/tasks', 'CategoryController@tasks');
    });