James James - 2 years ago 147
PHP Question

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' => 'testingphpunit@phpunittest.com', '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
file to
and in my
file too.

I have also updated the stock

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

Where am I going wrong?

Answer Source

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" => "testingphpunit@phpunittest.com", "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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download