我的测试:
class FloorStackTest extends TestCase
{
use RefreshDatabase, WithFaker, DatabaseMigrations;
protected $endPoint = '/endpoint';
public function test_unit_type_note_added_successfully()
{
$this->signIn();
$this->withoutExceptionHandling();
$unitType = UnitType::factory()->create();
$note = $this->faker()->sentence(3);
$resp = $this->ajaxPost($this->admin_route.$this->endPoint."/".$unitType->property_version_id."/save-ut-note",[
'notes' => [
[
"ut_note_id" => "utn_".$unitType->id,
"note" => $note
]
]
])->assertStatus(Response::HTTP_OK);
$results = [
'notes' => $note
];
//i could print upto here
dd('hit');
$this->assertDatabaseHas(UnitType::class,$results);
//but could not print here
dd('hit');
}
}我正在使用sqlite进行测试,我使用的是laravel 8(它之前是从laravel 5更新的,只是为了确认)
在上面的代码中,你可以看到我可以print hit的地方。
我正在使用.env.testing
DB_CONNECTION=sqlite
DB_DATABASE="database/test.sqlite"
DB_FOREIGN_KEYS=false我已经在使用:use RefreshDatabase了,但它仍然显示错误。完整的错误是:
Tests\Feature\FloorStackTest::test_unit_type_note_added_successfully
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: App\Models\UnitType (SQL: select count(*) as aggregate from "App\Models\UnitType" where ("notes" = Eveniet incidunt consequuntur dolore est.))我的模型UnitType有这个
use SoftDeletes, HasFactory;
protected $table = 'unit_types';
protected $guarded = ['id'];
protected $dates = ['created_at','updated_at','deleted_at'];发布于 2021-10-06 15:20:50
首先,请注意,将模型或完全限定的类名传递给assertDatabaseHas方法只在该框架的版本8开始可用。请看下面的签名更改:
Signature in v7:protected $this assertDatabaseHas(string $table, array $data, string|null $connection = null)。
Signature in v8:protected $this assertDatabaseHas(Model|string $table, array $data, string|null $connection = null)。
最终,必须使用实际的表名进行断言。以下是文档中演示的方式:
$this->assertDatabaseHas('users', [
'email' => 'sally@example.com',
]);因此,如果您使用的是Laravel <8,则可以传递表名符串以获得所需的结果:
$this->assertDatabaseHas('unit_types', $results);另一种方法来自this answer,您仍然可以使用模型类来获取表名,而不是对字符串进行硬编码。
如下所示:
$this->assertDatabaseHas((new UnitType)->getTable(), $results);在Laravel 8中,该方法将获取一个模型,并通过此方法运行它以获得表名:
protected function getTable($table)
{
return is_subclass_of($table, Model::class) ? (new $table)->getTable() : $table;
}在这里,table可以是模型实例,也可以是完全限定的类名(new UnitType或UnitType::class)。只需注意,它必须扩展Model基类,以便Laravel正确解析它,否则它只会将类名字符串传递给查询。
https://stackoverflow.com/questions/69468269
复制相似问题