首页 > 解决方案 > 使用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 存在的城市,但没有任何效果。

标签: laraveltestingphpunit

解决方案


问题是DatabaseMigrationstrait 会在每次测试后重置数据库,因此运行测试时数据库中没有用户。

这意味着您当前正在传递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]);
}

推荐阅读