Php Laravel中的测试未拾取集合属性
我在Laravel 7中进行了如下测试:Php Laravel中的测试未拾取集合属性,php,laravel,Php,Laravel,我在Laravel 7中进行了如下测试: <?php namespace Tests\Feature\Http\Controllers\Auth; use App\User; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tes
<?php
namespace Tests\Feature\Http\Controllers\Auth;
use App\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class LoginControllerTest extends TestCase
{
use DatabaseMigrations;
/**
* A basic feature test example.
*
* @return void
*/
public function testLoginPractitioner()
{
$user = factory(User::class, 1)->make();
dump($user);
$response = $this->post('/api/login', [
'phone_number' => $user->phone_number,
'password' => $user->password
], [
'Accept' => 'application/json',
'Content_Type' => 'application/json'
]);
$this->assertDatabaseHas('users', [
'phone_number' => $user->phone_number,
]);
}
}
}))
当我转储在测试中创建的用户对象时,我可以看到它有一个phone_number属性:
#attributes: array:6 [
"email" => "leonora.tromp@example.com"
"email_verified_at" => "2021-01-31 11:25:02"
"phone_number" => "12326385883"
"password" => "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi"
"remember_token" => "Oy8DfAonMu"
"is_admin" => false
]
1) Tests\Feature\Http\Controllers\Auth\LoginControllerTest::testLoginPractitioner
Exception: Property [phone_number] does not exist on this collection instance.
但我的测试一直失败,我收到这条消息,好像它没有电话号码属性:
#attributes: array:6 [
"email" => "leonora.tromp@example.com"
"email_verified_at" => "2021-01-31 11:25:02"
"phone_number" => "12326385883"
"password" => "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi"
"remember_token" => "Oy8DfAonMu"
"is_admin" => false
]
1) Tests\Feature\Http\Controllers\Auth\LoginControllerTest::testLoginPractitioner
Exception: Property [phone_number] does not exist on this collection instance.
此外,即使我使用了我确信在数据库中的数字,断言也会失败。为什么会发生这种情况?您的问题是,
$user
是一个集合
,当您为工厂
提供要创建的模型数量时,它将返回一个包含案例1中创建的模型的集合
实例。其次,对于要保存到数据库的模型,您应该调用create()
,而不是make()
将用户创建代码更改为以下应该可以解决此问题
$user = factory(User::class)->create();
如果一次需要创建多个用户,则需要将其从集合中取出。由于您似乎对集合
感到困惑,可能阅读上的内容是明智的。make()
不会插入到数据库中<代码>创建()。