我在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');
UserNotificationsController:
<?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?
亲切的问候,
休伯特
答案 0 :(得分:0)
//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);
}