简体   繁体   English

laravel assertDatabaseHas() 测试方法不起作用

[英]laravel assertDatabaseHas() testing method doesn't work

I'm using Laravel 5.4 and PHPUnit 6.5.5.我正在使用 Laravel 5.4 和 PHPUnit 6.5.5。 I keep getting the following error when using Laravel's assertDatabaseHas() method in my tests.在我的测试中使用 Laravel 的assertDatabaseHas()方法时,我不断收到以下错误。

Error: Call to undefined method Illuminate\Http\Response::assertDatabaseHas()

This is my code fragment using assertDatabaseHas() :这是我使用assertDatabaseHas()代码片段:

$response = $this->withSession(['user_id' => $this->user_id])
    ->json('post',
        route('some_route'),
        $request //an array 
    );

    $request['myuser_id'] = $this->user_id;

    $response->assertStatus($expected['code'])
        ->assertDatabaseHas('profiles',$request);

I also tried to use $this->assertDatabaseHas() , but a new error appeared:我也尝试使用$this->assertDatabaseHas() ,但出现了一个新错误:

TypeError: Argument 2 passed to PHPUnit\Framework\Assert::assertThat() must be an instance of PHPUnit\Framework\Constraint\Constraint, instance of Illuminate\Foundation\Testing\Constraints\HasInDatabase given, called in /project_path/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php on line 22

I searched for a while for the problem's solution and found this question , but downgrading PHPUnit version to 5.* didn't work for me.我搜索了一段时间以寻找问题的解决方案并找到了这个问题,但是将 PHPUnit 版本降级到 5.* 对我不起作用。

assertDatabaseHas() always worked, you were just using it incorrectly and a change in Laravel versions would not have fixed your problem. assertDatabaseHas()始终有效,您只是使用不正确,Laravel 版本的更改不会解决您的问题。

You're dealing with two separate entities here – an HTTP response and a database entry – and they need to be treated as such.您在这里处理两个独立的实体——一个 HTTP 响应和一个数据库条目——它们需要被这样对待。 The return from a method such as json() or assertStatus() is an instance of Illuminate\\Http\\Response and has no database methods. json()assertStatus()等方法的返回是Illuminate\\Http\\Response的实例,并且没有数据库方法。

Keep these things separate: make the HTTP request and check the response, then check the database.将这些事情分开:发出 HTTP 请求并检查响应,然后检查数据库。

$this
    ->withSession(['user_id' => $this->user_id])
    ->json('post', route('some_route'), $request)
    ->assertStatus($expected['code']);

$request['myuser_id'] = $this->user_id;

$this->assertDatabaseHas('profiles', $request);

I upgraded my laravel version from 5.4.37 to 5.5.40 and problem solved.我将 Laravel 版本从 5.4.37 升级到 5.5.40,问题解决了。 assertDatabaseHas() works fine now. assertDatabaseHas() 现在工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM