首页 > 解决方案 > Laravel - phpunit 更新方法失败,我不知道为什么

问题描述

这是我第一次编写测试,所以我为更新方法写了一个,我不知道我做错了什么,如果有更好的测试方法请告诉我,提前谢谢

路线

Route::group(['prefix' => 'categories' , 'namespace' => 'App\Http\Controllers\Admin'] , function () {
    Route::post('create', 'CategoryController@store')->name('category.store');
    Route::put('update/{category}', 'CategoryController@update')->name('category.update');
});

这是我的控制器

控制器

public function update(Request $request , Category $category)
{
    $category->update($request->all());
}

测试

/** @test */
public function a_category_can_be_updated()
{
    $this->withoutExceptionHandling();
    $this->post(
        route('category.store'),
        [
            'name' => 'Food',
            'slug' => 'food-and-drinks',
        ],
    );

    $category = Category::first();
    $this->put(
        route('category.update', $category->id),
        [
            'name' => 'Food and',
        ],
    );
    // dd($category);

    $this->assertEquals('Food and', $category->name);
    $this->assertEquals('Food-and', $category->slug);
}

错误来自测试

  • Tests\Feature\CategoriesTest > a category can be updated
  Failed asserting that two strings are equal.

  at F:\newProject\tests\Feature\CategoriesTest.php:66
     62▕             ],
     63▕         );
     64▕         // dd($category);
     65▕
  ➜  66▕         $this->assertEquals('Food and', $category->name);
     67▕         $this->assertEquals('Food-and', $category->slug);
     68▕     }
     69▕ }
     70▕

  1   F:\newProject\vendor\phpunit\phpunit\phpunit:61
      PHPUnit\TextUI\Command::main()
  --- Expected
  +++ Actual
  @@ @@
  -'Food and'
  +'Food'

模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Category extends Model
{

    protected $table = 'categories';
    public $timestamps = true;

    use SoftDeletes;

    protected $dates = ['deleted_at'];
    protected $fillable = array('name', 'slug', 'parent_id');

    public function posts()
    {
        return $this->belongsToMany('App\Models\Post');
    }


    //slugging the Category-name
    public function setSlugAttribute($value)
    {
        $this->attributes['slug'] = Str::slug($this->attributes['name']);
    }

    public function scopeParent()
    {
         return Category::whereNull('parent_id');
    }

}

让我知道代码发生了什么,在此先感谢

标签: phplaravelphpunit

解决方案


如“IGP”所述,您必须$category->fresh()在执行更新后使用。但是将其分配给您$category,如下所示:$category = $category->fresh();

查看 Laravel 文档了解详细信息:Eloquent ORM Refreshing Models


推荐阅读