Laravel sail - 测试返回错误:目标类 RestApiController 不存在

问题描述 投票:0回答:1

我收到错误消息,控制器不存在,但它存在

路线:

Route::middleware(['check.team.role'])->group(function () {
...
Route::get('/api/v1/folder/{folder}', 'App\Http\Controllers\RestApiController@getFolderById');
...
});

控制器应用程序/Http/Controllers/RestApiController.php


namespace App\Http\Controllers;

use App\Models\AccessMaterial;
use App\Models\User;
use App\Models\Team;
...

class RestApiController extends Controller
{
    protected $noteService;
    protected $taskService;
    protected $voteService;
    protected $CourseService;
    protected $teamService;
    protected $teamId;

    
    public function __construct(NoteService $noteService, TaskService $taskService, VoteService $voteService, CourseService $courseService, TeamService $teamService)
    {
        
    $this->middleware('auth.custom_sanctum');
        
        $this->noteService = $noteService;
        $this->taskService = $taskService;
        $this->voteService = $voteService;
        $this->courseService = $courseService;
        $this->teamService = $teamService;
    $this->teamId = Team::requested() ? Team::requested()->id : null;
                
        
    }
...

    public function getFolderById(UserFolder $folder) {
        
        try {
        
            $folder = UserFolder::findOrFail($folder->id);
            
            if($folder->team_id != $this->teamId) {
                return response()->json(['success' => false, 'message' => 'Team error'], 403);
            }
            
            
            $notes_ids = UserNote::where('folder_id', $folder->id)->pluck('id')->toArray();
            $tasks_ids = UserTask::where('folder_id', $folder->id)->pluck('id')->toArray();
            $votes_ids = UserVote::where('folder_id', $folder->id)->pluck('id')->toArray();
            $folder->notes = $notes_ids;
            $folder->tasks = $tasks_ids;
            $folder->votes = $votes_ids;
            
            $courses_ids = Course::where('folder_id',$folder->id)->where('user_id','!=',null)->pluck('id')->toArray();
            $folder->courses = $courses_ids;

            
            return response()->json(['success'=>true,'folder'=>$folder]);
            
        } catch (ModelNotFoundException $e) {
            return response()->json(['success' => false, 'message' => 'Folder not found'], 404);
        }
    }
...
}

测试:


namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

use Illuminate\Support\Str;

use App\Models\User;
use App\Models\UserFolder;
use App\Models\UserNote;
use App\Models\UserTask;
use App\Models\UserVote;
use App\Models\Course;
use App\Models\Team;

use Illuminate\Database\Eloquent\Factories\Factory;
use Database\Factories\UserFactory;
use Database\Factories\TeamFactory;
use Database\Factories\UserTaskFactory;
use Database\Factories\UserFolderFactory;
use Database\Factories\UserNoteFactory;
use Database\Factories\UserVoteFactory;
use Database\Factories\CourseFactory;

class RestApiOtherTest extends TestCase
{
    use RefreshDatabase;
    
    public function testServerResponse()
    {
        $user = \Database\Factories\UserFactory::new()->create();
        $teamA = Team::factory()->create();
        $teamA->users()->attach($user->id,['role'=>'hr']);
        $this->actingAs($user);

      
        $folder = UserFolder::factory()->create();

        $note = UserNote::factory()->create(['folder_id' => $folder->id]);
    

        $response = $this->getJson("/api/v1/folder/{$folder->id}");
        $response->assertStatus(200);
        $response->assertJson(['success' => true]);

    }   
...
}

当我进行测试时:./vendor/bin/sail test 我收到错误:

[2024-04-06 11:36:43] local.ERROR:目标类 [App\Http\Controllers\RestApiController] 不存在。 {“userId”:“9bbdffa8-b3f8-4980-834b-0a667dcedc32”,“异常”:“[对象](Illuminate\Contracts\Container\BindingResolutionException(代码:0):目标类[App\Http\Controllers\RestApiController]不存在。位于 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php:914) [堆栈跟踪] #0 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(795): Illuminate\Container\Container->build() #1 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(957): Illuminate\Container\Container->resolve() #2 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(731): Illuminate\Foundation\Application->resolve() #3 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(942): Illuminate\Container\Container->make() ...

我尝试运行

./vendor/bin/sail test
,我期望测试能够通过,但我收到 500 错误,找不到控制器类

更新1

我发现如果我使用

use PHPUnit\Framework\TestCase;

而不是

use Tests\TestCase

我收到另一个错误:

  FAILED  Tests\Feature\RestApiOtherTest > server response                                                                                   Error
  Call to a member function connection() on null

  at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1819
    1815▕      * @return \Illuminate\Database\Connection
    1816▕      */
    1817▕     public static function resolveConnection($connection = null)
    1818▕     {
  ➜ 1819▕         return static::$resolver->connection($connection);
    1820▕     }
    1821▕
    1822▕     /**
    1823▕      * Get the connection resolver instance.

      +13 vendor frames
  14  tests/Feature/RestApiOtherTest.php:37

我认为工厂有问题吗?但不知道具体是什么

laravel docker testing
1个回答
0
投票

您的解决方法应该是定义这样的路线:

Route::get(
    '/api/v1/folder/{folder}', 
    [\App\Http\Controllers\RestApiController::class, 'getFolderById'],
);

Laravel 自 Laravel 8.x+ 起停止使用

'App\Http\Controllers\RestApiController@getFolderById'
作为类和方法的定义,用于路由定义,请查看 Laravel 10.x 文档

最后提示,每次您需要在测试中使用 Laravel 或它的任何功能时,您必须使用

Tests\TestCase
,而不是
PHPUnit\Framework\TestCase
。如果你使用最后提到的一个,你将永远不会加载 Laravel,所以任何需要/使用 Laravel 的东西都不会工作。

© www.soinside.com 2019 - 2024. All rights reserved.