There seems to be some good suggestions here: https://stackoverflow.com/questions/34767309/better-way-for-testing-validation-errors
It looks like people reach for the response and assert it contains an error bag with the errors you are expecting
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a test that checks the type of file being uploaded. It works but I also wanted to check the validation errors.
Im using PHP 7.4, phpunit 5.5.4 and Laravel 6.18.13.
/** @test */
public function any_file_type_other_than_pdf_doc_and_docx_cant_be_uploaded()
{
Storage::fake('documents');
$client = factory(Client::class)->create();
$user = factory(User::class)->create([
'admin' => true,
'client_id' => null
]);
$report = factory(Report::class)->create([
'user_id' => $user->id,
'client_id' => $client->id
]);
$type = factory(DocumentType::class)->create();
$this->actingAs($user);
$file = UploadedFile::fake()->create('document.png', 999);
$this->json('POST', 'documents/'.$report->id, [
'file' => $file,
'type' => $type->id,
]);
// Assert the file was stored...
Storage::disk('local')->assertMissing("public/documents/{$file->hashName()}");
}
I have tried the following.
$this->json('POST', 'documents/'.$report->id, [
'file' => $file,
'type' => $type->id,
])->assertSessionHas('errors');
Missing key 'errors'
so tried
$response = $this->json('POST', 'documents/'.$report->id, [
'file' => $file,
'type' => $type->id,
]);
$response->assertSessionHasErrors('file', null, 'The file must be a file of type: doc, docx, pdf.');
got Failed asserting that null matches expected 'The file must be a file of type: doc, docx, pdf.'. Expected :The file must be a file of type: doc, docx, pdf. Actual :null and have also tried numerous other ways with no luck.
Uploading the wrong type returns the user to the upload form and flashes Errors: The file must be a file of type: doc, docx, pdf.
Anyone know how to check for this in my test?
Ah wait, you are using json
What about
$response->assertJsonValidationErrors(array $data);
Please or to participate in this conversation.