如何在单元测试laravel中正确获取错误以及禁用csrf检查?

时间:2019-03-11 05:30:39

标签: 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->body = $request->input('body');
        return response(["success"], 200);
    }

我创建了一个测试,该测试仅存储数据并检查响应是否为200。 还请向我展示如何使该测试对测试更好。但是我得到404 error我不知道这是什么错误。如何显示错误,我需要配置什么设置? 测试:

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);
    }

phpunit错误:

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.

1 个答案:

答案 0 :(得分:1)

我假设您在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应该在中间件层中实现,并且在所有测试请求中添加_token既繁琐又愚蠢,因此您应该仅在测试中禁用中间件:

use Illuminate\Foundation\Testing\WithoutMiddleware;

class MyControllerTest {
    use WithoutMiddleware;

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