Laravel工厂未返回正确的对象数据

时间:2019-01-22 03:21:15

标签: php laravel phpunit factory

我在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,没有空字符串,什么也没有。似乎是什么问题?如果我将工厂生成的任何内容保存到变量中,而不是立即将其返回,则可以看到该名称已被填充,但是在返回该名称之后,什么也没有发生,

2 个答案:

答案 0 :(得分:0)

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

要打印,请使用phpunit -v

答案 1 :(得分:0)

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

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

您没有将属性传递给父构造函数。雄辩的构造器在构造器中接受模型的属性,但您的上层构造器不接受它们,也不将其传递给父级。

将其更改为此:

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

顺便说一句,您正在重写Eloquent的构造函数,但是您在其中什么也没做。您确定要覆盖吗?

相关问题