Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit is returning 404 when it should be 200

I've never written test cases before and am attempting to do this for an API I have written.

I'm trying to call a route with a post request and so am using the below:

public function testRequestCorrectApiKey()
    {
        //Request with X-Authorization sending correct API Key
        $response = $this->call('POST', '/authenticate', ['email' => '[email protected]', 'password' => 'phpunittest', [], [], ['X-Authorization' => '123workingapikey123']]);

        $this->assertEquals(200, $response->status());
    }

This is always failing with the error:

Failed asserting that 404 matches 200

This would naturally indicate that it is sending the request to the wrong path. How can I ensure it is being posted to the correct URL and how can I see what it is trying to reach?

I've tried updating the APP url in my .env file to http://localhost/gm-api/public and in my config/app.php file too.

I have also updated the stock TestCase.php with:

protected $baseUrl = 'http://localhost/gm-api/public';

Where am I going wrong?

like image 978
James Avatar asked Nov 09 '22 16:11

James


1 Answers

I got around this, and personally think this is a better way to do it, by simply using Guzzle to run the tests.

/**
 * Send a request with the correct API Key
*/
public function testRequestCorrectApiKey()
{
    $key = ApiKey::find(1);

    //Request with X-Authorization sending correct API Key
    $path = 'authenticate';
    $client = new Client(['base_uri' => env('APP_URL', 'http://localhost/gm-api/public/')]);
    $response = $client->request("POST", $path, ["email" => "[email protected]", "password" => "phpunittest", "headers" => ["X-Authorization" => $key->key ]]);
    $status_code = $response->getStatusCode();

    $this->assertEquals(200, $status_code);
}

The benefit of this, is you can just set the Base URL inside the .env file with APP_URL and it is good to go.

I'm unsure why I couldn't get $this->call() to work after changing the $baseUrl in the default test case - I can only assume it was still hitting the wrong URL. However, using Guzzle has solved this for me and is actually testing the configuration of the server too - given PHPUnit spins up its own version, yet this is testing the current server environment.

like image 119
James Avatar answered Nov 15 '22 05:11

James