我们有一些传统的laravel项目,它们在课堂上使用正面.
use Cache;
LegacyClass
{
public function cacheFunctionOne()
{
$result = Cache::someFunction('parameter');
// logic to manipulate result
return $result;
}
public function cacheFunctionTwo()
{
$result = Cache::someFunction('parameter');
// different logic to manipulate result
return $result;
}
}
我们最近的项目使用了基础laravel类的依赖注入,facades代表了hinted at by Taylor Otwell himself个.(我们对每个类使用构造函数注入,但为了保持示例简短,这里我使用方法注入并使用单个类.)
use Illuminate\Cache\Repository as Cache;
ModernClass
{
public function cacheFunctionOne(Cache $cache)
{
$result = $cache->someFunction('parameter');
// logic to manipulate result
return $result;
}
public function cacheFunctionTwo(Cache $cache)
{
$result = $cache->someFunction('parameter');
// different logic to manipulate result
return $result;
}
}
我知道facades can be mocked
public function testExample()
{
Cache::shouldReceive('get')
->once()
->with('key')
->andReturn('value');
$this->visit('/users')->see('value');
}
这很适合unit tests人.我试图理解的问题是,这些外表是否被"全球"嘲笑.
例如,假设我正在编写一个集成测试(在模拟服务的同时测试几个相互连接的类,而不是使用实时服务的端到端测试),该测试在某个时候执行两个单独的类which contain the same facade that calls the same method with the same parameters.
在这些被调用的类之间,有一些复杂的功能,可以使用相同的参数更改facades方法返回的数据*
$modernClass->cacheFunctionOne($cache); // easily mocked
// logic that changes data returned by laravel Cache object function 'someFunction'
$modernClass->cacheFunctionTwo($cache); // easily mocked with a different mock
我们的现代类很容易测试,因为facade所代表的底层类被注入到每个类中(在本例中,每个方法).这意味着我可以创建两个单独的mock,并将它们注入每个类(方法)以模拟不同的结果.
$legacyClass->cacheFunctionOne();
// logic that changes data returned by laravel Cache object function 'someFunction'
$legacyClass->cacheFunctionTwo();
不过,在遗留系统中,模拟的facade应该是"全局"的,因此当facade在每个类中运行时,the exact same value is returned.
我这样想对吗?
*I understand this example may seem completely redundant from a code architecture and testing point of view, but I am stripping out all real functionality to try and give some sort of 'simple' example of what I am asking.