laravel - 使用actingAs的测试方法存在问题
问题描述
我有这个代码:
/** @test */
public function testBasicExample()
{
$user = User::find(1);
// $user = factory(User::class)->create();
$response = $this->actingAs(User::find(1))->json('POST', '/store/ad', [
'title' => 'Hello World',
'city' => 1,
'phone' => '666555555',
'description' => 'fasd asd as d asd as d asd as d asd as d asd as d asd as da sd asd',
'user_id' => 1
]);
$response
->assertStatus(201)
->assertJson([
'created' => true,
]);
}
不幸的是,此时我遇到了第一个问题。它看不到用户表。
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: users (SQL: select * from "users" where "users"."id" = 1 limit 1)
我正在寻找如何解决我的问题,我发现我必须使用DatabaseMigrations。所以我补充说
use Illuminate\Foundation\Testing\DatabaseMigrations;
class ExampleTest extends TestCase
{
use DatabaseMigrations;
//...
}
但现在我有新的问题。
TypeError:传递给 Illuminate\Foundation\Testing\TestCase::actingAs() 的参数 1 必须实现接口 Illuminate\Contracts\Auth\Authenticatable,给定 null
所以我实现了
use Illuminate\Contracts\Auth\Authenticatable;
class ExampleTest extends TestCase
{
use DatabaseMigrations;
use Authenticatable;
//...
}
它产生了新的错误:
Tests\Feature\ExampleTest 不能使用 Illuminate\Contracts\Auth\Authenticatable - 它不是一个特征
我该如何解决我的问题?我该如何测试呢?
@编辑
我发现了问题,但我不知道为什么它不起作用。我有这个规则来验证城市
'city' => 'required|integer|exists:cities,id'
问题是最后一条规则:exists:cities,id。我尝试了不同的 id 存在的城市,但没有任何效果。
解决方案
问题是DatabaseMigrations
trait 会在每次测试后重置数据库,因此运行测试时数据库中没有用户。
这意味着您当前正在传递null
以下行:
$this->actingAs(User::find(1))
您必须先使用factory
帮助程序创建用户:
$user = factory(User::class)->create();
以下应该可以解决您的问题:
1 - 删除以下内容:
use Authenticatable;
不知道你为什么要添加这个,异常清楚地表明传递给的参数$this->actingAs()
必须实现Authenticatable
接口而不是当前类。
2 - 将您的测试更改为以下内容:
/** @test */
public function testBasicExample()
{
$this->actingAs(factory(User::class)->create())
->json('POST', '/store/ad', [
'title' => 'Hello World',
'city' => 1,
'phone' => '666555555',
'description' => 'fasd asd as d asd as d asd as d asd as d asd as d asd as da sd asd',
'user_id' => 1
])
->assertStatus(201)
->assertJson(['created' => true]);
}
推荐阅读
- javascript - 我想在类中声明对象的值,并且只在我声明一个新类时调用键。我能做什么?
- sql - Postgres 函数 - 使用后备解析字段
- java - 我错过了 TestNG 代码中的重要内容吗?
- android - Android TV 应用程序屏幕在打开侧边菜单时被切断
- c# - MongoDB 集合设计以链接记录
- c++ - 为什么需要,在二叉树中添加一个节点需要一个参数;在链表中添加节点需要两个参数吗?(C++)
- mongodb - JOI 或 express-validator 与 Mongodb 验证
- google-docs-api - 如何向我的 gmail 帐户授予对 bot 的访问权限
- php - 防止使用多循环/ PHP的替代方法
- javascript - 使用变量在输入数组之间切换