It's my first time getting into unit tests.
I've installed PHPUnit and set up my directory structure to store all my test files, so what's left is actually writing the unit tests for my application.
Having never written any unit tests before, the obstacles I'm facing with this class are:
- How do I thoroughly test an autoloader class?
- How can I play with the
spl_autoload_register()function so that it does things what it needs to do? For example if it's set to throw an exception upon any errors so I can test if it does that. - How would I go about testing all my methods (of which some are private)?
I've tried searching online for some answers but I found only this answer, and from what I understand from it is that I can test if the loader works by actually just using the class as if it's in a production environment and then check if the classes exists, but does this really thoroughly unit tests the entire autoloader class?
I would appreciate some help in steering me into the right direction of what/how I should go about writing the tests for this class. Am I thinking about it all wrong? Would this be considered implementation detail that I should not be unit testing?
This is my implementation of the PSR-4 specification:
namespace Libraries;
class Psr4ClassAutoloader
{
private $mappings = [];
public function __construct($prepend = false)
{
spl_autoload_register([$this, 'loadClassFile'], true, $prepend);
}
public function mapPrefix($prefix, array $baseDirs, $prepend = false)
{
if (!isset($this->mappings[$prefix])) {
$this->mappings[$prefix] = [];
}
if ($prepend) {
$baseDirs = array_reverse($baseDirs);
foreach ($baseDirs as $baseDir) {
array_unshift($this->mappings[$prefix], $baseDir);
}
return;
}
$this->mappings[$prefix] = array_merge($this->mappings[$prefix], $baseDirs);
}
public function unregister()
{
spl_autoload_unregister([$this, 'loadClassFile']);
}
private function loadClassFile($className)
{
if (!$filePath = $this->findClassFile($className)) {
return false;
}
require_once $filePath;
return true;
}
private function findClassFile($className)
{
foreach ($this->mappings as $prefix => $baseDirs) {
if (strpos($className, $prefix) !== 0) {
continue;
}
foreach ($baseDirs as $baseDir) {
$filePath = $baseDir . substr($className, strlen($prefix) + 1) . '.php';
$filePath = str_replace('\\', DIRECTORY_SEPARATOR, $filePath);
if (is_file($filePath)) {
return $filePath;
}
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire