I got the “Failed asserting that 200 is identical to 404” while using Slim
and phpunit
. But the API works fine when manually testing.
After some digging, I realized that phpunit
did not like the way I included files in my app – if replacing require_once
with require
where used, the test outputs Fatal error: Cannot redeclare class \DBClass in database.php on line 11
.
So, in layman terms, phpunit reads the test files inside itself and then runs each of the tests with their instantiation commands. The only problem is that when you include your original application, the required files will be required more than once: leading to “disaster”. 🙂
Therefore, the solution I found was using a Singleton for the class defining the application:
<?php
namespace Tests;
use \Api\App as ApiAPP;
class App
{
private static $instance = null;
protected function __construct()
{
}
protected function __clone()
{
}
public static function getInstance()
{
// Return instance if existing
if (isset(self::$instance)) {
return self::$instance;
}
//
// Create a new instance, store it and return it
//
// Get the configuration
$settings = require __DIR__ . '/../src/settings.php';
// Create the app
self::$instance = (new PHPapiAPP($settings))->get();
//
// Return the instance
//
return self::$instance;
}
}
Code language: HTML, XML (xml)
Also, remember autoload-dev
in composer.json
.