1

Is it possible to print the message out from the error bag when testing API's using unit test? Yes it already shows the exception but it does not specify exactly what and in which validation the error is.

To make it clear, please have a look at this:

Tests:  1 failed, 23 passed, 3 pending
   Illuminate\Validation\ValidationException
   The given data was invalid

And what I'm expecting:

Tests:  1 failed, 23 passed, 3 pending
   Illuminate\Validation\ValidationException
   The given data was invalid, [
       'errors' => [all the validation errors listed here]
   ]

UPDATE

Already tried this but doesn't work:

// inside setUp method
$this->withoutExceptionHandling();

// inside test method
$this->postJson($uri, $this->newUser)
    // ->dumpSession()
    // ->dumpHeader()
    ->dump();

Also please, have a look at my script:

public function testCustomerCanStoreNewUser()
{
    $this->actingAs($this->customer, 'api');

    $uri = route('users.store');
    $this->postJson($uri, $this->newUser)
        ->dumpSession()
        ->dumpHeaders()
        ->dump()
        ->assertCreated()
        ->assertJsonStructure(['success', 'data']);

    $this->assertDatabaseHas('users', $this->newUser);
}
Yura
  • 1,937
  • 2
  • 19
  • 47
  • When you do `postJson` the response object should contain the validation result unless you're doing manual validation . – apokryfos Aug 30 '20 at 09:17
  • Excuse me, I don't get it.. I've updated my question, please have a look. – Yura Aug 30 '20 at 09:22
  • Try removing the `withoutExceptionHandling` part to get the correct validation exception response. – apokryfos Aug 30 '20 at 15:09
  • By removing `withoutExceptionHandling`, it only shows the status code which is 422. We know that is a validation error, but it does not tell us in what field the error is. – Yura Aug 31 '20 at 05:37
  • The response content should contain the validation errors – apokryfos Aug 31 '20 at 06:13

1 Answers1

-1

You can ->assertStatus(422) which is the status code laravel responds with when the validation fails.

422 Unprocessable Entity

Flo Espen
  • 450
  • 4
  • 10
  • Not helpful if you want the specific rule that fails. But this is usually all I do when testing the validation. – Flo Espen Aug 30 '20 at 09:10
  • Thank you for answering, but I do not want to assert the status, i want to show the error – Yura Aug 30 '20 at 09:13