Last Updated: February 25, 2016
·
6.771K
· ajeliuc

Symfony2 unit testing uploaded file.

For example you want to unit test your libraries that works with symfony's UploadedFile

You need:
1. Create file
2. Initialize new Uploaded file object
3. Test

class MyUploadFileTest extends PHPUnit_Framework_TestCase
{
    protected $file;
    protected $image;

    public function setUp()
    {
        $this->file = tempnam(sys_get_temp_dir(), 'upl'); // create file
        imagepng(imagecreatetruecolor(10, 10), $this->file); // create and write image/png to it
        $this->image = new UploadedFile(
            $this->file,
            'new_image.png'
        );
    }

    public function testMime()
    {
        $res = $file->getMimeType();

        $this->assertEquals('image/png', $res);
    }

    public function tearDown()
    {
        unlink($this->file);
    }
}