@dana
To test file uploads in PHPUnit, you can follow these steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public function testFileUpload() { // Create a fake file to upload $file = sys_get_temp_dir() . '/testfile.txt'; // This will create the temporary file in the system's temporary directory file_put_contents($file, 'Test file content'); // Upload the file using a POST request $response = $this->uploadFile($file); // Assert the response to check if the file was uploaded successfully $this->assertEquals(200, $response->getStatusCode()); $this->assertFileExists('path/to/uploaded/files/testfile.txt'); // Replace the path with the actual upload directory path // Clean up the temporary file unlink($file); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private function uploadFile($file) { $client = new GuzzleHttpClient(); return $client->request('POST', 'http://example.com/upload', [ 'multipart' => [ [ 'name' => 'file', 'contents' => fopen($file, 'r'), 'filename' => basename($file) ] ] ]); } |
Make sure to adjust the URL and form field name according to your application's upload endpoint.
1
|
phpunit --bootstrap vendor/autoload.php tests/YourTestCase.php |
Replace vendor/autoload.php
with the path to your autoload.php file, and tests/YourTestCase.php
with the path to your test case file.
These steps should allow you to test file uploads in PHPUnit.