【问题标题】:How do I run a test for an array of json objects sent through the request?如何对通过请求发送的 json 对象数组运行测试?
【发布时间】:2021-06-05 02:18:02
【问题描述】:

我正在通过请求传递一个 json 对象数组以在控制器中进行验证:

控制器

public function store(Request $request)
{
    $this->validate($request, [
        'situation' => 'required',
    ]);
    
    $emotions= ['data' => $request->input('emotions')];
    

    $emotionsValidation = \Illuminate\Support\Facades\Validator::make($emotions, [
        'data.*.id' => 'integer|between:1,70',
        'data.*.intensity' => 'integer|between:0,100',
        'data.*.new_intensity' => 'integer|between:0,100'
    ]);

    
    if($emotionsValidation->fails()) {
        
        return response(['error' => 'There was a problem with the emotions you submitted.'],422);
    }

    $emotions= ['data' => $request->input('emotions')];
    

    $emotionsValidation = \Illuminate\Support\Facades\Validator::make($emotions, [
        'data.*.id' => 'integer|between:1,70',
        'data.*.intensity' => 'integer|between:0,100',
        'data.*.new_intensity' => 'integer|between:0,100'
    ]);

    
    if($emotionsValidation->fails()) {
        return response(['error' => 'There was a problem with the emotions you submitted.'],422);
    }
    
    //Return record resource
}

验证工作正常,但测试并没有像应有的那样通过:

测试

/** @test */
public function a_records_json_emotions_must_be_integers()
{
    $this->actingAs($creator = factory('App\User')->create());

    $thought = [
        'user_id' => 1,
        'situation' => 'A situation',
        'emotions' => json_decode("[{'id': 2000, 'intensity': 100, 'new_intensity': 20}]")
    ];

    //dd(json_encode("[{'id': 2000, 'intensity': 100, 'new_intensity': 20}]"));
    $response = $this->json('POST', '/api/thought/record', $thought )
        ->assertStatus(422);
}

当我取消注释 dd(json_encode("[{'id': 2000, 'intensity': 100, 'new_intensity': 20}]")); 时,我得到:""[{'id': 2000, 'intensity': 100, 'new_intensity': 20}]""

测试信息

  1. Tests\Feature\UserThoughtRecordsTest::a_thought_records_json_emotions_must_be_integers 预期状态码 422,但收到 201。 无法断言 422 与 201 相同。

如何让这个测试通过?

【问题讨论】:

    标签: laravel validation phpunit


    【解决方案1】:

    json_decode() 将返回 null,如果您在双引号字符串中使用单引号,如下所示:

    json_decode("[{'id': 2000, 'intensity': 100, 'new_intensity': 20}]")

    您需要对字符串使用单引号,对 JSON 使用双引号,如下所示:

    json_decode('[{"id": 2000, "intensity": 100, "new_intensity": 20}]', true)

    然后,Laravel 验证可以将您的请求验证为 PHP 数组。

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 2019-09-17
      • 1970-01-01
      • 2017-05-19
      • 2013-02-27
      • 2017-05-04
      相关资源
      最近更新 更多