我正在使用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时出现此错误:
错误:未找到“配置”类
我如何对这个班级进行单元测试?
谢谢。
答案 0 :(得分:1)
而不是扩展PHPUnit\Framework\TestCase
,您应该扩展Tests\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以获取更多信息。
答案 1 :(得分:0)
尝试包括这样的
use Illuminate\Support\Facades\Config;
答案 2 :(得分:0)
最好在代码中模拟依赖项。在这种情况下,您依赖于外部类(Config)。通常我会这样测试:
// 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注入构造函数来测试它。