Ad

Laravel 5.2 : Test Uploaded File Is Valid: IsValid() On A Non-object

- 1 answer

I'm trying to test my uploaded file function. I'm mocking the UploadedFile, but I get this error from my controller:

[Symfony\Component\Debug\Exception\FatalErrorException]
Call to a member function isValid() on a non-object

The uploaded file (mocked UploadedFile) will be received by my controller, but I can't call any method of UploadedFile.

My controller:

class FileController extends Controller
{
    public function upload(Request $request)
    {
        return $request->file('file')->isValid();
    }
}

My test looks as follows:

class FileTest extends TestCase
{
    private $fileMock;

    public function setUp()
    {
        parent::setUp();

        $this->fileMock = Mockery::mock(Symfony\Component\HttpFoundation\File\UploadedFile::class,
        [
            'getClientOriginalName'      => public_path() . '/images/foo.jpg',
            'getClientOriginalExtension' => 'jpg',
            'image/jpeg',
            null,
            null,
            true
        ]);
    }

    /** @test */
    public function it_gets_an_uploaded_file()
    {
        $this->fileMock
        ->shouldReceive('isValid')
        ->once()
        ->andReturn(true);

        $this->call('POST', 'file/upload', [], [], ['file' => [$this->fileMock]]);
        $this->assertResponseOk();

    }

    public function tearDown()
    {
        Mockery::close();
    }
}
Ad

Answer

The problem is that $request->file('file') is an array. Therefore you need to change:

public function upload(Request $request)
{
    return $request->file('file')->isValid();
}

to this:

public function upload(Request $request)
{
    return $request->file('file')[0]->isValid(); 
}

in your FileController.

Ad
source: stackoverflow.com
Ad