作者:MIS-AMY_301 | 来源:互联网 | 2023-01-07 15:10
我正在为我的控制器编写一些测试,但我的一个测试不起作用.它倾向于搜索并将结果返回到页面.但它实际上是重定向到主页.这是我的代码:
use DatabaseMigrations;
protected $user;
public function setUp()
{
parent::setUp();
$this->seed();
$this->user = factory(User::class)->create(['role_id' => 3]);
}
/** @test */
public function test_manage_search_user()
{
$respOnse= $this->followingRedirects()->actingAs($this->user)->get('/manage/users/search', [
'choices' => 'username',
'search' => $this->user->username,
]);
$response->assertViewIs('manage.users');
$response->assertSuccessful();
$response->assertSee($this->user->email);
}
您应该使其工作的URL如下所示:
http://localhost/manage/users/search?choices=username&search=Test
我再次检查,看起来它没有在带有get请求的参数中给出.我怎样才能解决这个问题?
1> MathieuAucla..:
我有同样的问题试图测试GET
请求,你实际上不能传递参数$this->get('uri', [header])
但你可以通过使用$this->call
,如果你签入MakesHttpRequests.php你可以看到,this->get()
实际上是使用调用方法.
通过向get方法添加数组,您将更改请求标头,这就是您没有获取参数的原因.
public function get($uri, array $headers = [])
{
$server = $this->transformHeadersToServerVars($headers);
return $this->call('GET', $uri, [], [], [], $server);
}
public function call($method, $uri, $parameters = [], $COOKIEs = [], $files = [], $server = [], $cOntent= null)
{
$kernel = $this->app->make(HttpKernel::class);
$files = array_merge($files, $this->extractFilesFromDataArray($parameters));
$symfOnyRequest= SymfonyRequest::create(
$this->prepareUrlForRequest($uri), $method, $parameters,
$COOKIEs, $files, array_replace($this->serverVariables, $server), $content
);
$respOnse= $kernel->handle(
$request = Request::createFromBase($symfonyRequest)
);
if ($this->followRedirects) {
$respOnse= $this->followRedirects($response);
}
$kernel->terminate($request, $response);
return $this->createTestResponse($response);
}
因此,如果您要测试GET
请求,则必须执行以下操作:
$request = $this->call('GET', '/myController', ["test"=>"test"]);
在您的控制器中,您应该能够获得这样的参数:
public function myController(Request $request)
{
$requestCOntent= $request->all();
$parameter = $requestContent['test'];
}
2> Hyder B...:
我正在使用Laravel 5.X(更确切地说是5.6),您可以使用以下方式传递自定义参数:
$respOnse= $this->json('GET', '/url/endpoint',['params'=>'value']);