【问题标题】:Testing Laravel post requests using a Factory使用工厂测试 Laravel 发布请求
【发布时间】:2020-04-12 04:02:25
【问题描述】:

我正在为我的 Laravel 应用程序编写一些功能测试。我是 TDD 的新手,所以这对某些人来说似乎很明显。

LocationsFactory.php

use Faker\Generator as Faker;

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

LocationsTest.php

public function a_user_can_create_a_location(): void
{
    $this->withExceptionHandling();

    $user = factory(User::class)->make();
    $location = factory(Location::class)->make();


    $response = $this->actingAs($user)->post('/locations', $location);  // $location needs to be an array

    $response->assertStatus(200);
    $this->assertDatabaseHas('locations', ['name' => $location->name]);
}

TypeError: 传递给 Illuminate\Foundation\Testing\TestCase::post() 的参数 2 必须是数组类型,给定对象

我知道错误告诉我$location 需要是一个数组并且它是一个对象。但是,由于我使用的是工厂,所以它是作为对象出现的。有没有更好的方法在我的测试中使用工厂?

这似乎也有点不对劲:

$this->assertDatabaseHas('locations', ['name' => $location->name]);

由于我使用的是 faker,所以我不知道 name 会是什么。所以我只是检查生成的内容是否理想?

感谢您的任何建议!

编辑

做这样的事情很好(也许这就是解决方案)......

...
$user = factory(User::class)->make();
$location = factory(Location::class)->make();

$response = $this->actingAs($user)->post('/locations', [
    'name' => $location->name
]);

$response->assertStatus(200);
$this->assertDatabaseHas('locations', ['name' => $location->name]);

但是,假设我的location 有 30 个属性。这似乎很快就会变得丑陋。

【问题讨论】:

    标签: laravel-5 tdd


    【解决方案1】:

    Laravel 5

    使用toArray() 进行对象到数组的转换:参见以下示例

        $user = factory(User::class)->make();
        $location = factory(Location::class)->make();
    
        $response = $this->actingAs($user)->post('/locations', $location->toArray());
    
        $response->assertStatus(200);
        $this->assertDatabaseHas('locations', ['name' => $location->name]);
    

    【讨论】:

    • 我以为我已经尝试过了,但显然没有正确实施。非常感谢!
    【解决方案2】:

    您也可以使用raw,它将属性构建为一个数组。

    $user = factory(User::class)->make();
    $location = factory(Location::class)->raw();
    
    $response = $this->actingAs($user)->post('/locations', $location);
    
    $response->assertStatus(200);
    $this->assertDatabaseHas('locations', $location);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-06
      • 2016-06-01
      • 2021-12-06
      • 1970-01-01
      • 2016-12-01
      • 2021-09-28
      • 2018-06-27
      • 1970-01-01
      相关资源
      最近更新 更多