Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何正确地获取单元测试中的错误以及禁用csrf检查?_Unit Testing_Laravel 5_Phpunit - Fatal编程技术网

Unit testing 如何正确地获取单元测试中的错误以及禁用csrf检查?

Unit testing 如何正确地获取单元测试中的错误以及禁用csrf检查?,unit-testing,laravel-5,phpunit,Unit Testing,Laravel 5,Phpunit,我正在尝试在控制器中测试我的post方法。方法定义类似于: public function store(Request $request) { $article = new Article; $article->id = $request->input('article_id'); $article->title = $request->input('title'); $article-&g

我正在尝试在控制器中测试我的
post
方法。方法定义类似于:

    public function store(Request $request)
    {
        $article = new Article;

        $article->id = $request->input('article_id');
        $article->title = $request->input('title');
        $article->body = $request->input('body');
        return response(["success"], 200);
    }
我创建了一个测试,它只存储数据并检查响应是否为200。 还请告诉我如何使此测试更好地进行新测试。但是我得到了404错误,我不知道是什么错误。如何显示错误我需要配置哪些设置? 测试:

public function test_post_new_article(){
        $article = factory(Article::class)->make();
        $this->call('POST', 'article', [
            '_token' => csrf_token(),
            'article_id' => 6,
            'title'=>"hey",
            'body' => "this is a body"
        ])->assertStatus(200);
    }
There was 1 failure:

1) Tests\Unit\ExampleTest::test_post_new_article
Expected status code 200 but received 404.
Failed asserting that false is true.
phpunit错误:

public function test_post_new_article(){
        $article = factory(Article::class)->make();
        $this->call('POST', 'article', [
            '_token' => csrf_token(),
            'article_id' => 6,
            'title'=>"hey",
            'body' => "this is a body"
        ])->assertStatus(200);
    }
There was 1 failure:

1) Tests\Unit\ExampleTest::test_post_new_article
Expected status code 200 but received 404.
Failed asserting that false is true.

我假设您在
routes/api.php
中定义了路由,使得特定路由的前缀是
/api/

您必须调用API路由的完整路径:

    $this->call('POST', '/api/article', [
        '_token' => csrf_token(),
        'article_id' => 6,
        'title'=>"hey",
        'body' => "this is a body"
    ])->assertStatus(200);
此外,由于CSRF应该在您的中间件层中实现,并且将
\u token
添加到所有测试请求中既繁琐又愚蠢,因此您可能应该在测试中禁用中间件:

use Illuminate\Foundation\Testing\WithoutMiddleware;

class MyControllerTest {
    use WithoutMiddleware;

    ... public function testmyUnitTest() { ... }
}

哦,那真的很有帮助。。。你能帮我纠正我的错误吗?。。。我已将“显示错误”转为“不走运”。@ReyYoung如果您将
$this->call
行替换为我提供的那一行,它将修复您的404错误。