Laravel:我如何断言一个数组

问题描述

我正在为Seminar创建功能测试。一切都很好。我正在尝试更新功能测试以考虑研讨会日期。

每个Seminar可以有一个或多个日期,因此我将这些值另存为json字段:

// migration:

...

$table->json('dates');

...

这是我的Seminar模型的样子:

// Seminar.PHP

protected $casts = [
    'dates' => 'array',];

保存研讨会时,我返回的是json资源:

if ($seminar->save()) {
    return response()->json(new SeminarResource($seminar),200);
    ...

使用邮递员,我的Seminar看起来像这样:

...

"capacity": 100,"dates": [
    "2020-10-15","2020-10-16"
],...

到目前为止一切顺利!

在测试中,我正在测试可以创建一个研讨会。

$http->assertStatus(201)

->assertJson([
    'type' => 'seminars','id' => (string)$response->id,'attributes' => [
        'dates' => $response->attributes->dates,// General error: 25 column index out of range

我尝试将数组转换为字符串或资源中的值json_encode。我认为这不是正确的方法,因为我已经将值转换为模型中的数组。

如何断言我的dates返回一个数组?

 +"dates": array:2 [
      0 => "2020-10-15"
      1 => "2020-10-16"
    ]

谢谢您的建议!

编辑

dd($response->attributes->dates);是我得到的(正确)。

array:2 [
  0 => "2020-10-15"
  1 => "2020-10-16"
]

我不确定如何声明这样的数组。由于我使用伪造者生成日期,因此我真的不知道(或关心)日期是什么,只是想断言它实际上是一个数组。

我尝试过类似的事情:

 'dates' => ['*'],

但是,这只是向数组添加了另一个元素。

编辑2

如果我将数组设为字符串,

'dates' => json_encode($response->attributes->dates),

我会收到这样的错误


--- Expected
+++ Actual
@@ @@


-    'dates' => '["2020-10-15","2020-10-16"]',+    'dates' => 
+    array (
+      0 => '2020-10-15',+      1 => '2020-10-16',+    ),

在我的数据库中,值存储如下:

["2020-10-15","2020-10-16"]

我的实际测试如下:

$http->assertStatus(201)
            ->assertJsonStructure([
                'type','id','attributes' => [
                    'name','venue','dates','description','created_at','updated_at',],])
            ->assertJson([
                'type' => 'workshops','attributes' => [
                    'name' => $response->attributes->name,'venue' => $response->attributes->venue,'dates' => $response->attributes->dates,'description' => $response->attributes->description,'created_at' => (string)$response->attributes->created_at,'updated_at' => (string)$response->attributes->updated_at,]);

        $this->assertDatabaseHas('workshops',[
            'id' => $response->id,'name' => $response->attributes->name,]);

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)