在Laravel8中,单元测试时如何获取请求的url?

c9x0cxw0  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(345)

我想在Laravel8中编写一个单元测试来测试 POST 创建新实体的请求。在该请求中,一个 job_id 已创建,并且url具有 job_id 附加。我想找回它 job_id . 我该怎么做?
例如

$route = route( 'job.store', $payload );
$response = $this->followingRedirects()->post( $route );

这个 $response 应该重定向到以下内容 http://localhost:9080/sales/job/J00561 . 我想获取url,这样我就可以 job_id ,是 J00561 .
我该怎么做?

kupeojn6

kupeojn61#

对于这种情况-因为它不是和api,并且您无法从响应中获得创建的作业id-我建议如下:

//create
$createResponse = $this->post(route('job.store', $payload))
   -> assertSuccessful();

//get created job by params
$job = Job::where($payload)->find();
//check creation
$this->assertNotNull($job);

//assert redirect
$createResponse->assertRedirect($showRoute = route('job.show', $jobId));
$this->get($showRoute)->assertSuccessful();

下面是另一种方法—解析jobid的头位置—但在我看来,这种方法是错误的:

$createResponse = $this->post($route('job.store', $payload))
   ->assertSucceful();
$params = explode('/',parse_url($createResponse->headers->get('Location'))['path']);
$jobId = array_pop($params);
$createResponse->assertRedirect($showRoute = route('job.show', $jobId));
$this->get($showRoute)->assertSuccessful();

相关问题