首页 > 解决方案 > 在 laravel 的测试中的 getJson 没有被传递给控制器

问题描述

我在一个 Laravel 项目中进行了一个测试,在那里我做了一个 getJson 请求,应该返回一些答案。但是控制器中的方法没有受到影响。

考试

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class NotificationsTest extends TestCase
{
    use DatabaseMigrations;

    public function setUp(): void
    {
        parent::setUp();

        $this->signIn();
    }




    public function test_a_user_can_fetch_their_unread_notifications()
    {

        create(DatabaseNotification::class);

        $response = $this->getJson(url('/profiles') . '/' . auth()->user()->name . '/notifications')->json();

        $this->assertCount(1, $response);
    }

webp.php 中应处理此请求的行:

Route::get('/profiles/{user}/notifications', 'UserNotificationsController@index');

用户通知控制器:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\User;

class UserNotificationsController extends Controller
{
    public function __construct()
    {
        $this->middelware('auth');
    }

    public function index() {
        dd(" UsderNotificationsController-Index method hit");
        return auth()->user()->unreadNotifications;
    }


    public function destroy(User $user, $notificationId)
    {

        dd(' Destroy method hit');
        auth()->user()->notifications()->findOrFail($notificationId)->markAsRead();
    }
}

如果我用 phpunit 运行测试,我希望 index 方法中的 DD() 应该被执行。但事实并非如此。

我尝试了各种变体来生成 URI,但总是得到相同的结果。谁能告诉我为什么我没有生成正确的 URI?

亲切的问候,

休伯特

标签: laravelphpunit

解决方案


 //start by doing that : in your controller
Route::get('/profiles/notifications', 'UserNotificationsController@index');

  public function test_a_user_can_fetch_their_unread_notifications()
 {
   $this->withoutHandlingException();

    create(DatabaseNotification::class,['user_id'=>$this->signIn()->id]);
     $this->signIn()//i think it should return authenticated user

    $response = $this->get('/profiles/notifications')
                ->assertStatus(200);
   // $this->assertCount(1, $response);
    
}

-//在你的索引函数中

public function index() {
    dd(" UsderNotificationsController-Index method hit");
    return response()->json(auth()->user()->unreadNotifications,200);
}

推荐阅读