I have a Laravel 8 app that I'm working on where I need to use GET parameters (e.g. test?num=1
) but unfortunately, I don't appear to be able to figure out how to run the unit tests against this.
I've followed the guidance I can find online (including Laravel phpunit testing get with parameters, which looked very promising) however, none of the approaches seem to work.
To try and figure out the issue, I've created a VERY simple version and I'm getting the same behaviours. If I go to the URL directly it works as expected but the unit tests fail.
routes\web.php
Route::get('/test', 'TimeController@test')->name('myTest');
app\Http\Controllers\TimeController.php
public function test()
{
return $_GET['num'] ?? "Num not provided";
}
test\Unit\Http\Controllers\TimeControllerTest.php
/** @test */
public function num_test_1()
{
$params = ["num" => "1"];
$response = $this->get('/test?num=1');
$response->assertSeeText("1");
}
/** @test */
public function num_test_2()
{
$params = ["num" => "1"];
$response = $this->get('/test', $params);
$response->assertSeeText("1");
}
/** @test */
public function num_test_3()
{
$params = ["num" => "1"];
$response = $this->call('GET', '/test', $params);
$response->assertSeeText("1");
}
All three of the above tests fail with the message
Failed asserting that 'Num not provided' contains "1".
I have even gone to the lengths of deleting the node_modules
and vendor
folders just in case I had a corrupt PHPUnit package or something.
Am I missing anything obvious? This feels like something that should be pretty easy to do and something that a lot of people will have done before.
CodePudding user response:
It work fine.
You should change your method like this:
public function test(Request $request)
{
return $request->input('num') ?? "Num not provided";
}
Or with query
method:
public function test(Request $request)
{
return $request->query('num') ?? "Num not provided";
}