Php 使用登录用户测试POST请求
我需要为POST请求编写测试。他们中的大多数人需要登录用户(有时需要一些许可证)。我写了这个测试:Php 使用登录用户测试POST请求,php,laravel,testing,phpunit,Php,Laravel,Testing,Phpunit,我需要为POST请求编写测试。他们中的大多数人需要登录用户(有时需要一些许可证)。我写了这个测试: <?php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; use App\User; class ExampleTest extends TestCase { /** * A basic test example.
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use App\User;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
// $user = new User([
// 'id' => 1,
// 'name' => 'yisdfsdsh',
// 'password' => 'helloWorld',
// 'admin' => 1
// ]);
$user = User::find(1);
$response = $this->actingAs($user)->withHeaders([
'X-Header' => 'Value',
])->json('POST', '/change-password', ['password' => 'newpassword', 'confirmPassword' => 'newpassword']);
$response->assertStatus(201);
// $this->get('/')->assertStatus(200);
}
}
但它获得了500名。我怎么写这个测试?此控制器的方法需要更新用户的密码
@编辑
我试着用factory编写代码:
$user = factory(User::class)->create();
$response = $this->actingAs($user)->withHeaders([
'X-Header' => 'Value',
])->json('POST', '/change-password', ['password' => 'newpassword', 'confirmPassword' => 'newpassword']);
$response->assertStatus(201);
但我有同样的错误
Illumb\Database\QueryException:找不到驱动程序(SQL:PRAGMA-foreign\u-keys=ON;)
例如,您使用的是像SQLite这样的测试数据库吗?您应该使用Factory创建一个用户,而不是使用数据库中可能不存在的id=1来获取用户。我更新了我的帖子。我尝试使用factory,但它不起作用。您需要安装sqlite sudo apt get install php-sqlite3或brew install sqlite3
$user = factory(User::class)->create();
$response = $this->actingAs($user)->withHeaders([
'X-Header' => 'Value',
])->json('POST', '/change-password', ['password' => 'newpassword', 'confirmPassword' => 'newpassword']);
$response->assertStatus(201);