【问题标题】:Config class not found when unit testing laravel package单元测试laravel包时找不到配置类
【发布时间】:2017-07-05 09:24:16
【问题描述】:

我正在开发 Laravel (5.4) 包,并且正在尝试进行单元测试。我有这门课:

<?php

namespace Sample;

class Foo
{
    public function getConfig()
    {
        $config = \Config::get('test');

        return $config;
    }   
}

我有这个测试:

<?php

use PHPUnit\Framework\TestCase;
use Sample\Foo;

class FooTest extends TestCase
{
    public function testGetConfig()
    {
        $foo = new Foo;
        $config = $foo->getConfig();
    }
}

当我执行 phpunit 时出现此错误:

错误:找不到类“配置”

如何对这个类进行单元测试?

谢谢。

【问题讨论】:

  • 包括供应商自动加载

标签: php unit-testing laravel-5 phpunit package


【解决方案1】:

最好在代码中模拟依赖项。在这种情况下,您依赖于外部类(配置)。通常我是这样测试的:

// make sure the mock config facade receives the request and returns something
Config::shouldReceive('get')->with('test')->once()->andReturn('bla');

// check if the value is returned by your getConfig().
$this->assertEquals('bla', $config);

显然,您需要在测试中导入 Config 门面。

但是:我会在我的真实代码中的构造函数中注入 Config 类,而不是使用外观。但这就是我... :-)

类似的东西

class Foo
{
    /** container for injection */
    private $config;

    public function __construct(Config config) {
        $this->config = $config;
    }

    public function getConfig()
    {
        $config = $this->config->get('test');

        return $config;
    }   
}

然后通过在构造函数中注入一个模拟 Config 来测试它。

【讨论】:

    【解决方案2】:

    您应该扩展Tests\TestCase,而不是扩展PHPUnit\Framework\TestCase

    <?php
    namespace Tests\Unit;
    
    // use PHPUnit\Framework\TestCase;
    use Tests\TestCase;
    use Sample\Foo;
    
    class FooTest extends TestCase
    {
        public function testGetConfig()
        {
            $foo = new Foo;
            $config = $foo->getConfig();
        }
    }
    

    此外,Config 或其他 Laravel 外观可能无法在 @dataProvider 方法中工作,请参阅 Laravel framework classes not available in PHPUnit data provider 了解更多信息。

    【讨论】:

      【解决方案3】:

      尝试像这样包含

      use Illuminate\Support\Facades\Config;
      

      【讨论】:

      • 不同的错误:RuntimeException:尚未设置外观根。
      猜你喜欢
      • 2016-03-16
      • 2013-06-22
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 2015-09-24
      相关资源
      最近更新 更多