使用laravel执行单元测试以加载自定义设置文件时出错

时间:2016-03-22 11:42:25

标签: php solr laravel-5 solarium

当我从浏览器运行该服务时,它可以工作,但如果我执行测试文件,我会收到此错误:

1) Api\Domain\Tests\ServiceTest::testSetUp
RuntimeException: A facade root has not been set.

/WWW/api/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:210
/WWW/api/src/Api/Infrastructure/Domain/Model/SolrBaseRepository.php:30
/WWW/api/src/Api/Infrastructure/Domain/Model/SolrBaseRepository.php:30
/WWW/api/src/Api/Domain/Tests/ServiceTest.php:80

文件配置:config / solr.php

return array(
    'endpoint' => array(
        'localhost' => array(
            'host' => '192.168.1.100',
            'port' => 8080,
            'path' => '/solr/clients/',
        )
    )
);

Solr base repository:

use Illuminate\Support\Facades\Config;

abstract class SolrBaseRepository
protected $client;


    /**
     * SolrBaseRepository constructor.
     */
    public function __construct(){
        $this->client = new \Solarium\Client(Config::get('solr'));
    }
}

如果我改变

$this->client = new \Solarium\Client(Config::get('solr'));

通过

$this->client = new \Solarium\Client(array(
            'endpoint' => array(
                'localhost' => array(
                    'host' => '192.168.1.100',
                    'port' => 8080,
                    'path' => '/solr/clients/',
                )
            )
        ));

测试工作正常。 ServiceTest:Api / Domain / Tests / ServiceTest.php

class ServiceTest extends \PHPUnit_Framework_TestCase{
public function testSetUp()
    {
        $this->setUp();
        $this->solrServicesRepository = New SolrServicesRepository();
    }
}

我试图解决它从this page添加到我的ServiceTest.php:

use \Illuminate\Container\Container as Container;
use \Illuminate\Support\Facades\Facade as Facade;

/**
* Setup a new app instance container
* 
* @var Illuminate\Container\Container
*/
$app = new Container();
$app->singleton('app', 'Illuminate\Container\Container');

/**
* Set $app as FacadeApplication handler
*/
Facade::setFacadeApplication($app);

但这对mi不起作用。

1 个答案:

答案 0 :(得分:2)

已经有一段时间了,但是当我遇到同样的问题时,我找到了答案。

在测试中,您需要在初始化时调用父设置函数:

class ExampleTest extends TestCase
{

    public function setUp()
    {
        parent::setUp();
        $this->faker = Faker\Factory::create();
        // other lines of code that you need
    }

    public function testWithFacades()
    {
         //now it works
    }
}