Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel facade class not found when mocked in a unit test

I might be missing something here but I have a very simple helper class that creates a directory:

// Helper class

<?php namespace MyApp\Helpers;

    use User;
    use File;

    class FileSystemHelper
    {
        protected $userBin = 'users/uploads';

        public function createUserUploadBin(User $user)
        {
            $path = $this->userBin . '/' . $user->id;

            if ( ! File::isDirectory($path))
            {
                File::makeDirectory($path);
            }
        }
    }

And associated test here:

// Associated test class

<?php 

    use MyApp\Helpers\FileSystemHelper;

    class FileSystemHelperTest extends TestCase {

        protected $fileSystemHelper;

        public function setUp()
        {
            $this->fileSystemHelper = new FileSystemHelper;
        }

        public function testNewUploadBinCreatedWhenNotExists()
        {
            $user = new User; // this would be mocked

            File::shouldReceive('makeDirectory')->once();

            $this->fileSystemHelper->createUserUploadBin($user);
        }
    }

However I get a fatal error when running the test:

PHP Fatal error: Class 'File' not found in /my/app/folder/app/tests/lib/myapp/helpers/FileSystemHelperTest.php

I've looked at the docs for mocking a facade and I can't see where I'm going wrong. Any suggestions?

Thanks

like image 935
Russ Back Avatar asked Jun 25 '13 09:06

Russ Back


2 Answers

I missed this in the docs:

Note: If you define your own setUp method, be sure to call parent::setUp.

Calling that cured the problem. Doh!

like image 51
Russ Back Avatar answered Oct 06 '22 16:10

Russ Back


it's because laravel framework is not loaded before using facade OR it because you are not using laravel php unit(TestCase class) here is a sample code to test case that are in app/ //attention to extends from TestCase not ()

/**
 * TEST CASE the application.
 *
 */
class TestCase extends Illuminate\Foundation\Testing\TestCase {

    /**
     * Creates the application.
     *
     * @return \Symfony\Component\HttpKernel\HttpKernelInterface
     */
    public function createApplication()
    {
        $unitTesting = true;

        $testEnvironment = 'testing';

        //this line boot the laravel framework so all facades are in your hand
        return require __DIR__.'/../../bootstrap/start.php';
   }

}

like image 42
Hamed Nova Avatar answered Oct 06 '22 15:10

Hamed Nova