Laravel Feature Test单测正常批量运行报404问题求助
问题
我用最新版Laravel编写Feature Test,两个测试用例单独运行都正常,但同时运行时最后一个用例返回404状态码,而非预期的400,怀疑存在缓存问题。附上测试代码及错误信息,请求排查原因。
测试代码:
class RegisterTest extends TestCase { use DatabaseTransactions; private $registerRoute = '/api/v1/auth/register'; /** @test */ public function user_can_register() { $testUserData = [ 'first_name' => 'John', 'last_name' => 'Doe', 'dob' => '1987-08-05', 'email' => 'test@example.com', 'password' => 'Password123!', ]; // Send a POST request to the login route with user's credentials $response = $this->post($this->registerRoute, $testUserData); // Assert that the registration was successful (status code 200) $response->assertStatus(200); // Assert that the user record exists in the database $response->assertJsonStructure(['email']); } /** @test */ public function user_cannot_register_with_weak_password2() { $testUserData = [ 'first_name' => 'John', 'last_name' => 'Doe', 'dob' => '1987-08-05', 'email' => 'test@example.com', 'password' => 'password', ]; // Send a POST request to the login route with user's credentials // here I was trying different ways to create the request to see if I could clear out the caching somehow. $request = Request::create($this->registerRoute, 'POST', $testUserData); $response = $this->app->handle($request); // Assert that the registration was successful (status code 200) $this->assertEquals(400, $response->getStatusCode()); } }
错误信息:
FAIL Tests\Feature\RegisterTest ✓ user can register 0.07s ⨯ user cannot register with weak password2 0.01s ─────────────────────────────────────────────────────────────────────────────────────── FAILED Tests\Feature\RegisterTest > user cannot register with weak password2 Failed asserting that 404 matches expected 400.
排查与解决
核心原因:测试请求方式不规范
第二个测试用例没有使用Laravel TestCase提供的标准请求方法,而是手动创建Request并让应用实例直接处理,这种方式跳过了测试框架的初始化逻辑,导致连续运行时路由无法正确匹配,最终返回404。
修复步骤
- 统一测试请求方式:将第二个测试里的手动请求代码替换为和第一个测试一致的
$this->post()方法,确保测试框架正确处理路由与环境:
/** @test */ public function user_cannot_register_with_weak_password2() { $testUserData = [ 'first_name' => 'John', 'last_name' => 'Doe', 'dob' => '1987-08-05', 'email' => 'test@example.com', 'password' => 'password', ]; $response = $this->post($this->registerRoute, $testUserData); $response->assertStatus(400); }
- 确认事务隔离有效性:你已经使用
DatabaseTransactionstrait,每个测试方法执行后都会自动回滚数据库操作,因此两个测试用例使用同一邮箱不会产生数据冲突,无需额外处理。 - 检查路由配置:确保
/api/v1/auth/register路由在routes/api.php中正确定义为POST方法,示例:
Route::post('/auth/register', [AuthController::class, 'register']);
为什么单独运行正常?
单独运行第二个测试时,应用实例初始化流程完整,手动创建的Request能正确匹配路由;但连续运行时,第一个测试后的应用状态变化导致手动处理的请求无法正确加载路由规则,从而返回404。
内容的提问来源于stack exchange,提问作者Joe Blogs
相关产品推荐
相关产品推荐

