Laravel 如何在没有中间件的情况下使用模型注入测试控制器?
当我测试这个时:Laravel 如何在没有中间件的情况下使用模型注入测试控制器?,laravel,phpunit,Laravel,Phpunit,当我测试这个时: use WithoutMiddleware; public function testPutSportOK() { $sport = Sport::first(); $sportName = 'Modification '.$sport->sport_name; $position = random_int(0,100); $post = [ 'sport_name' => $sportName,
use WithoutMiddleware;
public function testPutSportOK()
{
$sport = Sport::first();
$sportName = 'Modification '.$sport->sport_name;
$position = random_int(0,100);
$post = [
'sport_name' => $sportName,
'position' => $position
];
$response = $this->json('PUT', '/api/sports/'.$sport->id, $post);
$response->assertStatus(200);
测试失败,因为我在控制器中使用了模型注入。我知道这种注入需要“绑定”中间件。但由于我禁用了所有的中间件,所以无法进行注射
由于身份验证的原因,我禁用了中间件
我试图补充这一点:
$this->withMiddleware('bindings');
但还是一样
如何使用模型注入和无中间件测试控制器
编辑
添加带有模型注入的控制器:
public function update(Request $request, Sport $sport)
{
// var_dump($sport);
$validator = Validator::make($request->all(), [
'sport_name' => 'required',
'position' => 'required|int'
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
try {
// not necessary with the injection model
// $sport = Sport::findOrFail($id);
$sport->fill($request->all());
$sport->save();
return new SportResource($sport);
} catch (\Exception $ex) {
return response()->json($ex->getMessage(), 400);
}
}
从源代码中,您可以通过提供一组您想要禁用的中间软件来禁用“部分”中间软件(而不是全部禁用)
$this->withoutMiddleware([
\App\Http\Middleware\Authenticate,
\App\Http\Middleware\RedirectIfAuthenticated,
// Add more here
]);
最后我放弃了这个想法模型注入。选择路由和控制器之间的经典id通道 由于这一点,我的phpunit+postman测试工作得非常好,我不再对这个“绑定”中间件感到厌倦 当然,它需要在控制器中再写一行来读取数据库中相应的模型。但这只是一条线。我接受
祝你度过愉快的一天,多米尼克注射模型在哪里?你能展示你的完整代码吗?我添加了控制器的源代码,在其中你可以看到模型的注入。谢谢你为什么要禁用所有的中间件?我禁用了中间件,因为我的路由受到令牌“承载者”的保护。对于我的测试,我不需要它。但也许这不是一个好的做法?