10

I have the following code in one of my routes:

return Response::download('cv.pdf');

Any idea how to test this? I've tried to use shouldReceive() but that doesn't seem to work ('shouldReceive() undefined function....').

4

4 回答 4

7

$response->assertDownload() was added in Laravel 8.45.0:

Assert that the response is a "download". Typically, this means the invoked route that returned the response returned a Response::download response, BinaryFileResponse, or Storage::download response:

$response->assertDownload();

Learn More:

https://laravel.com/docs/8.x/http-tests#assert-download

于 2021-06-06T14:52:08.567 回答
3

EDIT: As pointed by @DavidBarker in his comment to the OP question

The Illuminate\Support\Facades\Response class doesn't actually extend Illuminate\Support\Facades\Facade so doesnt have the shouldRecieve() method. You need to test the response of this route after calling it in a test.


So if you want to test your download functionality, you can try checking the response for errors with:

$this->assertTrue(preg_match('/(error|notice)/i', $response) === false);
于 2014-01-13T13:03:03.910 回答
3

You can assert that the status code is 200

$this->assertEquals($response->getStatusCode(), 200);

because sometimes you might have some data returned that match "error" or "notice" and that would be misleading.

I additionally assert that there's an attachment in the response headers:

$this->assertContains('attachment', (string)$response);
于 2016-02-15T11:17:04.060 回答
0

You can use Mockery to mock the download method, for this you will need to mock ResponseFactory.

public function testDownloadCsv()
{
    $this->instance(
        ResponseFactory::class, Mockery::mock(ResponseFactory::class, function ($mock) {
        $mock->shouldReceive('download')
            ->once()
            ->andReturn(['header' => 'data']);
    }));

    $response = $this->get('/dowload-csv');

    $response->assertStatus(Response::HTTP_OK);
    $response->assertJson(['header' => 'data']); // Response
}
于 2019-09-04T18:45:18.297 回答