提供商
namespace App\Providers;
class ElasticSearchProvider extends ServiceProvider
{
public function register()
{
$hosts = [
'elasticsearch'
];
$instance = Elasticsearch\ClientBuilder::create()
->setHosts($hosts)
->build();
$this->app->instance('App\ESClient', $instance);
}
}
实际课程
命名空间App \ Mappings;
class Categories implements Mappable
{
public $es;
public function __construct(App\ESClient $es)
{
$this->es = $es;
}
public function setMapping()
{
}
public function getMapping()
{
}
}
测试用例
use App\Mappings\Categories;
class CategoriesTest extends TestCase
{
private $instance;
public function testShouldReturnElasticSearchInstance()
{
$categories = new Categories();
dd($categories->es);
}
}
1)CategoriesTest :: testShouldReturnElasticSearchInstance ErrorException:参数1传递给 App \ Mappings \ Categories :: __ construct()必须是。的实例 App \ Mappings \ App \ ESClient,没有给出,
所以在这里DI不起作用,或者我注册了一些错误,我们怎么测试呢?
由于
答案 0 :(得分:0)
您可以将Mockery用于测试用例。因此,在此示例中,您的测试用例将如下所示:
use App\ESClient;
use App\Mappings\Categories;
use Mockery as m;
class CategoriesTest extends TestCase
{
private $instance;
public function testShouldReturnElasticSearchInstance()
{
$esClient = m::mock(ESClient::class);
$categories = m::mock(new Categories($esClient));
dd($categories->es);
}
}
这将为您提供一个模拟的App\ESClient
类,您将注入App\Mappings\Categories
的部分模拟类。当您学习在单元测试中使用mockery时,您会发现这是测试目的的最佳选择 - 因为模拟对象(和Laravel Facades)可以在测试时覆盖并且可以捕获测试中对象的每个方法调用(使用{ {1}}模拟类的方法。)