I am new to laravel and I am trying to build a PHPUnit testing using phpunit
command. However, the test keeps saying Expected status code 200 but received 400
. And when I test same uri on Postman, it works perfectly fine.
When I use phpunit
command, request()->segment(1)
would return null
. However, making requests with Postman would return correct value for request()->segment(1)
which is 'api'.
I am using dingo package for api request.
Any suggestion or advice would be appreciated.
Thank you.
Edited: I've found the problem which was that when I run command line like phpunit
, request()
would recognize the command as request. So, how could I go around?
Here is my test code
ClientTest.php
<?php
namespace Tests\Unit\Client;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class ClientTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$response = $this->get('/api/v1/clients/1');
$response->assertStatus(200);
}
}
And here is my api route code
route/api.php
<?php
use Dingo\Api\Routing\Router;
if ( request()->segment(1) === 'api' ) {
$apiRouter = app(Router::class);
$apiVersion = strtolower(request()->segment(2));
$apiRouter->version($apiVersion, function ($apiRouter) use ($apiVersion)
{
$pathPrefix = 'App\Http\Controllers\Api\V1';
$apiRouter->get($apiVersion.'/clients/{id}', $pathPrefix.'\Client\ClientController@index');
});
}