【问题标题】:Problem with testing method with actingAs使用actingAs的测试方法存在问题
【发布时间】:2020-07-03 20:48:15
【问题描述】:

我有这个代码:

/**  @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,
        ]);
}

不幸的是,此时我遇到了第一个问题。它看不到 users 表。

Illuminate\Database\QueryException: SQLSTATE[HY000]: 一般错误:1 没有这样的表:用户(SQL:select * from "users" where "users"."id" = 1 个限制 1)

我正在寻找如何解决我的问题,我发现我必须使用 DatabaseMigrations。所以我补充说

use Illuminate\Foundation\Testing\DatabaseMigrations;
class ExampleTest extends TestCase
{
    use DatabaseMigrations;
//...
}

但是现在我有新问题了。

TypeError:参数 1 传递给 Illuminate\Foundation\Testing\TestCase::actingAs() 必须实现 interface Illuminate\Contracts\Auth\Authenticatable, null given

所以我实现了

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 存在的城市,但没有任何效果。

【问题讨论】:

    标签: laravel testing phpunit


    【解决方案1】:

    问题是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]);
    }
    

    【讨论】:

    • 我不知道你在这条路线上做什么,所以我不能告诉你为什么你会收到这个状态码,但它可能与验证有关,尝试在开头添加$this->withoutExceptionHandling();你的测试,并检查错误。
    • 我找到了问题,但我不知道如何解决。我在我的帖子上显示它
    • @Kowal8856 和用户一样的错误,数据库是空的,没有城市,你要先创建一个城市进行测试。
    猜你喜欢
    • 2019-10-24
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2021-11-30
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多