laravel - 在 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?
亲切的问候,
休伯特
解决方案
//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);
}
推荐阅读
- excel - VBA function that will look in cell comment that have multiple lines for a specific line
- sonarqube - SonarCloud 代码覆盖率在 GitHub Actions 构建中保持为 0.0
- javascript - JS 递归地映射对象名称
- vbscript - 如何获取非内置对象 (API) 的参考
- android - 发布后是否可以更改 Android targetSdkVersion?
- html - 在由 div 组成的类似表格的结构中将列粘贴到左侧和顶部
- angular - 从Angular中的父路由组件向当前子路由添加查询参数
- sql - 有没有办法计算两次相同的日期列?
- angular - ngx-分页中的编号
- c++ - 在 C++ 中为无序映射获取给定输入键的错误值