为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel 路由上的 PHPunit 测试总是返回 404

Laravel 路由上的 PHPunit 测试总是返回 404

PHP
犯罪嫌疑人X 2023-08-19 16:50:52
我刚刚开始在我的 laravel 应用程序上编写 PHPUnit 路由测试,它通过浏览器和 Postman 运行良好,但不是通过 PHPunit。示例:在本次测试中public function test_getAll(){    $this->withoutExceptionHandling(); // If i comment this line I get the 404 and not the error shown below    $response = $this->get('/api/users');    $response->assertStatus(401);}我得到:PHPUnit 8.5.3 by Sebastian Bergmann and contributors..E                                                                  2 / 2 (100%)Time: 1.89 seconds, Memory: 8.00 MBThere was 1 error:1) Tests\Feature\Users\UserRoute_SuperAdminTest::test_getAllSymfony\Component\HttpKernel\Exception\NotFoundHttpException: GET http://localhost/cms/api/usersE:\www\projects\cms-php\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithExceptionHandling.php:126E:\www\projects\cms-php\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:415E:\www\projects\cms-php\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:113E:\www\projects\cms-php\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.php:468E:\www\projects\cms-php\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.php:258E:\www\projects\cms-php\tests\Feature\Users\UsersRoute-SuperAdmin_Test.php:45奇怪的是:如果我将 URL 更改为:$response = $this->get('http://anythingatallinhere/api/users');我得到了我应该得到的 401 响应。更多上下文信息来解决问题。我的 env APP_URL 是APP_URL=http://localhost/cms,我正在以这种方式动态注册路由:我有一个 CoreServiceProvider ,其启动过程如下:public function boot()    {       [...]        $moduleController = app()->make(ModuleController::class);        $moduleController->registerCoreRoutes();       [...]如果我使用php artisan route:list它们,它们也都已正确注册。
查看完整描述

2 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

我最近遇到了类似的问题,但运行这些后它起作用了:

php artisan config:clear
php artisan config:cache

特别是如果您更改了 .env 文件中刚刚更改的 APP_URL。

您还可以尝试在 phpunit.xml 文件中processIsolation设置:true

<phpunit backupGlobals="false"
 backupStaticAttributes="false"
 bootstrap="bootstrap/autoload.php"
 colors="true"
 convertErrorsToExceptions="true"
 convertNoticesToExceptions="true"
 convertWarningsToExceptions="true"
 processIsolation="true"
 stopOnFailure="false">

编辑: 如果上述方法都不起作用,您还可以创建另一个.env.testing并将您的设置APP_URLhttp://localhost. PHPUnit 将使用该文件中的变量。无论您的应用程序的实际 URL 是什么,这都有效


查看完整回答
反对 回复 2023-08-19
?
芜湖不芜

TA贡献1796条经验 获得超7个赞

最简单的方法是通过添加以下行来http://localhostphpunit.xml文件中设置 APP_URL:

<server name="APP_URL" value="http://localhost"/>

如果您希望变量在.env测试期间仍然可用,则此方法是最好的。创建您自己的.env.testing文件将覆盖所有.env变量。


查看完整回答
反对 回复 2023-08-19
  • 2 回答
  • 0 关注
  • 85 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信