0
我的大多数单元测试都使用WithoutMiddleware,因此我可以测试控制器和资源端点。然而,路由模型绑定是一个中间件,所以控制器没有得到他们需要的模型。单元测试期间,如何使Laravel中的路由模型绑定工作?
我的大多数单元测试都使用WithoutMiddleware,因此我可以测试控制器和资源端点。然而,路由模型绑定是一个中间件,所以控制器没有得到他们需要的模型。单元测试期间,如何使Laravel中的路由模型绑定工作?
创建仅在测试期间运行的服务提供者。 - 首先确保你在phpunit.xml中设置了APP_ENV - 接下来为laravel创建服务提供者,如下图所示。 (不要忘了将它添加到配置/ app.php的供应商部分)
phpunit.xml
...<php>
<env name="APP_ENV" value="testing"/>
...
</php>...
配置/ app.php
...providers=>[..., App\Providers\PhpUnitServiceProvider::class, ...]
应用/供应商/ PhpUnitServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class PhpUnitServiceProvider extends ServiceProvider{
/**
* Map of classes you want route-model binding to work
* based on a variable name in the route.
*
* example: http://localhost/bank-accounts/{bank_account}
*
* @var array
*/
private static $map = [
\App\Financial\BankAccount::class => 'bank_account',
];
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot(){
//
}
/**
* We need to simulate route-model binding.
*
* @return void
*/
public function register(){
//
if(env('APP_ENV') == 'testing'){
$classes = array_keys(static::$map);
foreach($classes as $class){
$this->app->bind($class, function ($app) use ($class){
return self::factory($class, $app);
});
}
}
}
private static function factory($class, $app){
if(empty(static::$map[$class])){
return null;
}
$request = request();
$target = static::$map[$class];
if(empty($request->$target)){
return null;
}
$id = $request->$target;
return $class::find($id);
}
}