我正在处理laravel(5.4)软件包,我正在尝试进行单元测试。我有这个课:
<?php
namespace Sample;
class Foo
{
public function getConfig()
{
$config = Config::get('test');
return $config;
}
}
我有此测试:
<?php
use PHPUnitFrameworkTestCase;
use SampleFoo;
class FooTest extends TestCase
{
public function testGetConfig()
{
$foo = new Foo;
$config = $foo->getConfig();
}
}
当我执行phpunit时,我有一个错误:
错误:找不到类'config'
如何单元测试此类?
谢谢。
而不是扩展PHPUnitFrameworkTestCase
,您应该扩展TestsTestCase
:
<?php
namespace TestsUnit;
// use PHPUnitFrameworkTestCase;
use TestsTestCase;
use SampleFoo;
class FooTest extends TestCase
{
public function testGetConfig()
{
$foo = new Foo;
$config = $foo->getConfig();
}
}
此外,Config
或其他Laravel立面可能在@dataProvider
方法中不起作用,请参阅Phpunit数据提供商中的Laravel Framework类,以获取更多信息。
嘲笑代码中的依赖项是很好的做法。在这种情况下,您取决于外部类(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);
显然,您需要在测试中导入配置外观。
ut:我将在我的真实代码中注入构造函数中的配置类,而不是使用立面。但这就是我...: - )
类似这样的东西
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;
}
}
然后通过将模拟配置注入构造函数来测试。
尝试包括这样的
use IlluminateSupportFacadesConfig;