Laravel 9.x功能测试:带重定向中间件的接口断言200状态问题
解决Laravel 9 Feature Test中Location路由返回302的问题
问题根源
你的adminAuth中间件逻辑是检测到有效用户就重定向到仪表盘,所以测试时如果请求携带了认证用户(比如测试用例里提前登录了用户),访问/location会直接被跳走,返回302,根本到不了LocationController@index方法返回200。
可行解决方案
1. 用未认证请求访问
如果业务逻辑就是未登录用户才能访问Location列表页,那测试时直接发未认证请求就行:
public function test_location_index_returns_200() { $response = $this->get('/location'); $response->assertStatus(200); }
2. 测试时跳过adminAuth中间件
要是只想单独测控制器的返回逻辑,不想受中间件干扰,可以直接移除中间件:
public function test_location_index_returns_200() { $this->withoutMiddleware(['adminAuth']); $response = $this->get('/location'); $response->assertStatus(200); }
提示:这种方式只适合测试控制器本身的业务,不包含中间件的校验流程。
3. 修正中间件逻辑(如果业务逻辑写反了)
如果实际业务是登录用户才能访问Location列表页,那你的adminAuth中间件逻辑搞反了,应该改成:
// adminAuth中间件修正示例 public function handle(Request $request, Closure $next) { if (!Auth::check()) { // 未登录用户才重定向 return redirect('/dashboard'); } return $next($request); }
修正后,测试时先登录有效用户再访问:
public function test_location_index_returns_200() { $user = User::factory()->create(); $this->actingAs($user); $response = $this->get('/location'); $response->assertStatus(200); }
内容的提问来源于stack exchange,提问作者Sachin Nagpal
相关产品推荐
相关产品推荐

