热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

PHPUnit:预期状态代码200但在Laravel中收到419

如何解决《PHPUnit:预期状态代码200但在Laravel中收到419》经验,为你挑选了2个好方法。

我想测试删除方法,但我没有从PHPUnit获得预期的结果.我在运行测试时收到此消息:

 Expected status code 200 but received 419. Failed asserting that false is true.
 /vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:77
 /tests/Unit/CategoriesControllerTest.php:70

Laravel版本:5.5

感谢您的任何帮助!

控制器构造函数:

public function __construct()
{
    $this->middleware('auth');

    $this->middleware('categoryAccess')->except([
        'index',
        'create'
    ]);
}

控制器方法:

public function destroy($categoryId)
{
    Category::destroy($categoryId);

    session()->flash('alert-success', 'Category was successfully deleted.');

    return redirect()->action('CategoriesController@index');
}

categoryAccess中间件:

public function handle($request, Closure $next)
{
    $category = Category::find($request->id);

    if (!($category->user_id == Auth::id())) {
        abort(404);
    }

    return $next($request);
}

分类型号:

protected $dispatchesEvents = [
    'deleted' => CategoryDeleted::class,
];

事件监听器

public function handle(ExpensesUpdated $event)
{
    $category_id = $event->expense->category_id;

    if (Category::find($category_id)) {
        $costs = Category::find($category_id)->expense->sum('cost');

        $category = Category::find($category_id);

        $category->total = $costs;

        $category->save();
    }
}

PHPUnit删除测试:

use RefreshDatabase;

protected $user;

public function setUp()
{
   parent::setUp();
   $this->user = factory(User::class)->create();
   $this->actingAs($this->user);
}

/** @test */
public function user_can_destroy()
{
    $category = factory(Category::class)->create([
        'user_id' => $this->user->id
    ]);

    $respOnse= $this->delete('/category/' . $category->id);

    $response->assertStatus(200);

    $response->assertViewIs('category.index');
}

piscator.. 18

缓存配置文件后,可以通过运行来解决此问题php artisan config:clear.



1> piscator..:

缓存配置文件后,可以通过运行来解决此问题php artisan config:clear.



2> Maraboc..:

有时在测试中,您需要禁用中间件才能继续:

use Illuminate\Foundation\Testing\WithoutMiddleware;

class ClassTest extends TestCase
{
    use WithoutMiddleware; // use this trait

    //tests here
}

如果你想为一个特定的测试用途禁用它们:

$this->withoutMiddleware();


推荐阅读
author-avatar
gengjiang3_946
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有