How to add headers to test?

Published 1 week ago by chillcaw

I'm using Lumen, but there is no information in the Lumen documentation on how to do this. So I followed the Laravel docs:

public function testUpdateMethodSuccess()
{
        $response = $this->withHeaders([
          'HTTP_Authorization', $this->token
        ])->json('POST', 'users/3', ['name' => 'Sally']);

        $response->assertResponseStatus(422);
}

Whether I use ->header or ->withHeaders I get a 'call to undefined method error' from phpunit

Best Answer (As Selected By chillcaw)
Borisu

I think the correct way is to use a fourth argument in the json function:

$this->json('POST', 'users/3', ['name' => 'Sally'], ['HTTP_Authorization' => $this->token]);

Try it.

Borisu
Borisu
1 week ago (76,680 XP)

I think the correct way is to use a fourth argument in the json function:

$this->json('POST', 'users/3', ['name' => 'Sally'], ['HTTP_Authorization' => $this->token]);

Try it.

chillcaw

Cheers! I fixed it like so:

public function testCreateMethodSuccess()
{
    $response = $this->json('POST', '3/users', ['name' => 'Sally'], ['HTTP_Authorization' => $this->token]);
    $this->assertEquals(422, $this->response->status());
}
Borisu
Borisu
6 days ago (76,680 XP)

You can also directly chain the assertion like so:

public function testCreateMethodSuccess()
{
    $this->json('POST', '3/users', ['name' => 'Sally'], ['HTTP_Authorization' => $this->token]);
        ->assertStatus(422);
}

cheers

Please sign in or create an account to participate in this conversation.