【问题标题】:Laravel facade class not found when mocked in a unit test在单元测试中模拟时找不到 Laravel 外观类
【发布时间】:2013-06-22 01:33:53
【问题描述】:

我可能在这里遗漏了一些东西,但我有一个非常简单的帮助类来创建一个目录:

// 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);
            }
        }
    }

以及相关的测试:

// 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);
        }
    }

但是我在运行测试时遇到了一个致命错误:

PHP 致命错误:在 /my/app/folder/app/tests/lib/myapp/helpers/FileSystemHelperTest.php 中找不到类“文件”

我查看了模拟外观的文档,但看不出哪里出错了。有什么建议吗?

谢谢

【问题讨论】:

    标签: phpunit laravel laravel-4 mockery


    【解决方案1】:

    我在文档中错过了这个:

    注意:如果您定义自己的 setUp 方法,请务必调用 parent::setUp。

    调用它可以解决问题。呵呵!

    【讨论】:

      【解决方案2】:

      这是因为在使用外观之前未加载 laravel 框架,或者因为您没有使用 laravel php 单元(TestCase 类) 这是一个示例代码,用于测试 app/ 中的用例 //注意扩展自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';
         }
      
      }
      

      【讨论】:

      • 为我工作 - 谢谢!出于某种原因,我的代码正在扩展 PHPUnit_Framework_TestCase 而不是 Illuminate 版本:/
      • Laravel 5.3 的有效答案(是的,我知道,旧的)。
      猜你喜欢
      • 2015-04-09
      • 2017-07-05
      • 2016-03-16
      • 2014-02-15
      • 2013-04-24
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      相关资源
      最近更新 更多