【问题标题】:LARAVEL cast colums JSON with feature test phpunitLARAVEL 使用功能测试 phpunit 转换列 JSON
【发布时间】:2020-12-22 02:50:10
【问题描述】:

没有通过我最后一个测试,将刚刚输入的字段与发送的字段进行比较,因为 json

我有以下字段:

public function up()
        {
            Schema::create('polls', function (Blueprint $table) {
                $table->id();
                $table->text('now');
                $table->json('paramJson');
                $table->enum('status', ['a', 'b', 'c','d'])->default('a');
            });
        }

投票模型:

protected $fillable=[
                'now',
           'paramJson',
            ];

//to cast that column from JSON to an array automatically (maybe it doesn't work)
protected $casts = [
                'paramJson' => 'array',
            ];

PollsController.php

public function add(Request $request)
    {
        $poll = Poll::create($request->all());
        return response()->json($poll, 201);
    }

功能/PollApiTest.php

    $data = [
       "now" => "Will Messi sign for City?",
       "parameters" : {"a"=> "yes", "b"=> "no"},
    ];

    $response = $this->post('/api/polls',$data);//add data in polls

    $response ->assertStatus(201);// assert Ok

    $response->assertJson($data);//assert Ok

    $response = $this->get('/api/poll');//get index polls

$this->assertSame($dataDbTest[0]['paramJson'],$data['paramJson']);//this test fails

最后一次测试失败,因为下面的错误

无法断言数组 &0 ( 'a' => '是的' 'b' => 'no' ) 等同于 '{"a": "yes", "b": "no"}'。

如果最后一次测试我是用 json_encode 做的:

$this->assertSame($dataDbTest[0]['paramJson'],json_encode($data['paramJson']));

--- Expected
+++ Actual @@ @@
-'{"a": "yes", "b": "no"}'
+'{"a":"yes","b":"no"}'

【问题讨论】:

    标签: mysql laravel api testing phpunit


    【解决方案1】:

    我觉得应该是这样的

    $this->assertSame(json_decode($dataDbTest[0]['paramJson']),$data['paramJson']);
    

    json_decode

    【讨论】:

      猜你喜欢
      • 2013-07-08
      • 2015-09-26
      • 2016-07-28
      • 2019-03-05
      • 2021-07-21
      • 2014-06-09
      • 2012-05-30
      • 2016-06-04
      • 2014-09-28
      相关资源
      最近更新 更多