![](/img/trans.png)
[英]Error:Call to a member function create() on null , unit test (Mockery)
[英]Error: Call to a member function store() on null when running test
我寫了以下測試:
public function testUserCanUploadFile()
{
$this->withoutExceptionHandling();
$this->signIn();
Storage::fake('public'); //Mock a disk
$file = UploadedFile::fake()->image('test.jpg'); //Upload a fake image.
$assortmentAttributes = Assortment::factory()->raw(); // Use the assortment factory.
$assortmentAttributes['image'] = $file; // Add a additional field in the assortment factory.
$this->post(route('assortments.store'), $assortmentAttributes)->assertRedirect(); // Post the fields to the assortmentcontroller store method. Expect a 403.
Storage::disk('public')->assertExists($file->hashName()); // Check if the field exists.
}
連同以下 controller:
$user = request()->user();
$assortment = $user->assortments()->create($request->all());
/*if ($request->hasFile('image')) {
dd($request->file('image'));
}*/
Assortment::create([
'file' => $request->file('file')->store('file', 'public')
]);
if ($request->wantsJson()) {
return response([], 204);
}
return back();
return redirect()->route('assortments.show', $assortment->slug)
->with('success','Verzameling is succesvol aangemaakt.');
}
當我運行測試時,沒有文件上傳。 我剛剛收到消息: Error: Call to a member function store() on null
。 它指的是我的 controller 中的第 56 行。 這是以下行:
'file' => $request->file('file')->store('file', 'public')
我不 go 出了什么問題。 當我將此代碼添加到我的 controller 時發生此錯誤:
Assortment::create([
'file' => $request->file('file')->store('file', 'public')
]);
if ($request->wantsJson()) {
return response([], 204);
}
return back();
在添加之前,我沒有收到錯誤消息,因為我使用了if
語句:
if ($request->hasFile('image')) {
dd($request->file('image'));
}
我該如何解決這個錯誤?
編輯:解決了錯誤。 將file
更改為image
。 現在我得到: Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: assortments.user_id (SQL: insert into "assortments" ("slug", "updated_at", "created_at") values (-1, 2020-12-17 13:11:11, 2020-12-17 13:11:11))
您在關鍵圖像下發送 UploadedFile
$assortmentAttributes['image'] = $file;
您正在嘗試使用 controller 中的密鑰file
檢索文件
Assortment::create([
'file' => $request->file('file')->store('file', 'public')
]);
//Here it should be
Assortment::create([
'file' => $request->file('image')->store('file', 'public')
]);
現在我得到: Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL 約束失敗: assortments.user_id (SQL: insert into "assortments" ("slug", "updated_at", "created_at") values (-1, 2020-12-17 13:11:11, 2020-12-17 13:11:11))
您可以嘗試通過關系創建分類記錄或手動添加 FK user_id
的值
//Assuming User model has a relation defined for Assortment as assortment()
$user->assortment()->create([
'file' => $request->file('image')->store('file', 'public')
]);
//OR
Assortment::create([
'user_id' => $user->id,
'file' => $request->file('image')->store('file', 'public')
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.