【问题标题】:Laravel factory not returning correct object dataLaravel 工厂没有返回正确的对象数据
【发布时间】:2019-06-15 11:35:39
【问题描述】:

我在 Laravel 5.7 中有以下工厂,调用它时没有返回任何内容:

<?php

use Faker\Generator as Faker;
use Illuminate\Database\Eloquent\Model;

$factory->define(App\Record::class, function (Faker $faker) {
    return [
        "name" => $faker->name,
    ];
});

而我的模型是:

<?php
namespace App;
use App\Product;
use Illuminate\Database\Eloquent\Model;

class Record extends Model
{
    protected $table = "records";

    protected $fillable = ["name"];

    function __construct()
    {
        parent::__construct();
    }
}

我在这里调用工厂:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\RefreshDatabase;

use App;
use App\Product;
use App\Record;
use App\User;

class RecordTest extends TestCase
{
    use RefreshDatabase;
    use WithoutMiddleware;

    /** @test */
    public function when_record_page_for_existing_record_is_accessed_then_a_product_is_displayed()
    {
        //$record = factory(App\Record::class)->make();
        $record = factory(App\Record::class)->create();
       echo "\n\n$record->name\n\n";

    }
}

打印时

$record->name

我什么都没有,不是 null,没有空字符串,什么都没有。似乎是什么问题?如果我将工厂生成的任何内容保存到变量中而不是立即返回它,我可以看到该名称正在被填充,但在返回它之后没有任何反应,它就消失了

【问题讨论】:

  • 你试过dd() $record 变量吗?
  • 是的,这不是打印问题,问题在于尝试打印的内容

标签: php laravel phpunit factory


【解决方案1】:

默认情况下phpunit 不会打印您的echo

如需打印,请使用phpunit -v

【讨论】:

  • phpunit 会打印回显语句。它会打印您在测试中指定的任何内容
【解决方案2】:

这段代码是有问题的部分:

function __construct()
{
    parent::__construct();
}

您没有将属性传递给父构造函数。 Eloquent 在构造函数中接受模型的属性,但你的重写构造函数不接受它们,也不将它们传递给父级。

改成这样:

function __construct(array $attributes = [])
{
    parent::__construct($attributes);
}

顺便说一句,您正在覆盖 Eloquent 的构造函数,但您没有在其中做任何事情。你确定你真的要覆盖它吗?

【讨论】:

  • 这确实是问题所在。非常感谢!我正在使用该构造函数,因为最初我的模型是从继承自 Model 的 Product 模型继承的。由于它也不起作用,我决定删除 Product 并仅使用直接从 Model 继承的 Record。现在我可以恢复到从 Product 继承的问题
  • 正确,但 $attributes 默认为空数组。方法签名是public function __construct(array $attributes = [])
  • @None 是对的,它会导致“__construct 中的参数太少”错误。属性必须是可选的。
猜你喜欢
  • 2020-04-16
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 1970-01-01
  • 1970-01-01
  • 2019-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多