phpunit测试返回302进行错误验证,为什么不返回422 [英] phpunit test returns 302 for bad validation, why not 422

查看:70
本文介绍了phpunit测试返回302进行错误验证,为什么不返回422的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个请求类,该类对于发布请求失败.当我用ajax调用它时,我得到422,因为验证规则失败.但是,当我使用phpunit测试具有相同值的相同路由时,它会返回302.

I have a request class that fails for a post request. When I call it with ajax I get an 422 because the validation rules failed. But when I use phpunit for test for the same route with same values, it returns a 302.

我也没有收到诸如需要foobar字段"之类的错误消息,只是302.

I also get no error messages like "field foobar is required" just the 302.

那么如何获取错误消息以检查它们是否相等?

So how can I get the error messages to check if they are equals or not?

这是我的测试代码:

//post exam
$this->post('modul/foo/exam', [
    'date' => '2016-01-01'
])
    ->assertResponseStatus(200);

//post exam again
$this->post('modul/foo/exam', [
    'date' => '2016-01-01'
])
    ->assertResponseStatus(302); //need to get 422 with th errors because its an api

推荐答案

FormRequest上的验证失败时,它将检查请求是否为ajax或是否接受json响应.如果是这样,它将返回带有422状态代码的json响应.如果不是,它将返回重定向到指定的URL(默认为以前的URL).因此,为了获得您要查找的失败的响应(422),您需要发出json请求或ajax请求.

When the validation on the FormRequest fails, it checks to see if the request was ajax or if it accepts a json response. If so, it will return a json response with the 422 status code. If not, it will return a redirect to a specified url (previous, by default). So, in order to get the response on failure you're looking for (422), you need to make a json request or an ajax request.

要发出json请求,您应该使用json()方法:

To make a json request, you should use the json() method:

//post exam
$this->json('POST', 'modul/foo/exam', [
        'date' => '2016-01-01'
    ])
    ->assertResponseStatus(200);

//post exam again
$this->json('POST', 'modul/foo/exam', [
        'date' => 'some invalid date'
    ])
    ->assertResponseStatus(422);

如果您认为比将方法作为参数传递看起来更干净,则还有getJson()postJson()putJson()patchJson()deleteJson()快捷方法.

There are also getJson(), postJson(), putJson(), patchJson(), and deleteJson() shortcut methods if you think that looks cleaner than passing the method as a parameter.

//post exam
$this->postJson('modul/foo/exam', [
        'date' => '2016-01-01'
    ])
    ->assertResponseStatus(200);

AJAX

要发出ajax请求,您需要添加ajax标头.为此,您可以继续使用post()方法:

//post exam
$this->post('modul/foo/exam', [
        'date' => '2016-01-01'
    ], ['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'])
    ->assertResponseStatus(200);

//post exam again
$this->post('modul/foo/exam', [
        'date' => 'some invalid date'
    ], ['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'])
    ->assertResponseStatus(422);

这篇关于phpunit测试返回302进行错误验证,为什么不返回422的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆