【问题标题】:getJson in test in laravel does not get passed to controller在 laravel 的测试中的 getJson 没有被传递给控制器
【发布时间】:2020-10-10 21:00:15
【问题描述】:

我在一个 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?

亲切的问候,

胡贝特

【问题讨论】:

    标签: laravel phpunit


    【解决方案1】:
     //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);
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 2023-03-29
      • 2023-04-03
      • 1970-01-01
      • 2017-09-24
      • 2015-12-08
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      相关资源
      最近更新 更多