I am learning TDD and I want to test my AutoLoader class, what needs to do the next job:
- do a check is the namespace is string
- do a check, is the path to directory parameter is a string
- do a check is the path to directory what I want to load is exists, directory and readable.
There will be more jobs, but I am newbee, so I need your opinion about my test:
<?php
namespace Myframework\Application\Autoloader;
class Autoloader {
/**
* @var string
*/
protected $namespace;
/**
* @var string
*/
protected $path;
public function __construct($namespace, $pathToClassesDirectory = '') {
if (!is_string($namespace)) {
throw new \Exception('Namespace must be string');
}
if (!is_string($pathToClassesDirectory)) {
throw new \Exception('Path to directory parameter should be string');
}
if (!file_exists($pathToClassesDirectory) || !is_dir($pathToClassesDirectory) || !is_readable($pathToClassesDirectory)) {
throw new \Exception('Path to directory is not accessible to read: "' . $pathToClassesDirectory . '"');
}
$this->namespace = $namespace;
$this->path = $pathToClassesDirectory;
}
}
The class:
<?php
use PHPUnit\Framework\TestCase;
/**
* @author vaso
*/
require_once '../system/Application/Autoloader/Autoloader.php';
class AutoloaderTest extends TestCase {
protected $Autoloader;
public function setUp() {
$this->Autoloader = new Myframework\Application\Autoloader\Autoloader(TEST_NAMESPACE, BASE_PATH);
}
public function tearDown() {
unset($this->Autoloader);
}
public function testConstructorCall() {
new Myframework\Application\Autoloader\Autoloader('nameSpaceAsString', BASE_PATH);
}
public function testConstructorCallNameSpaceIsNotStringException() {
$this->expectException('Exception');
new Myframework\Application\Autoloader\Autoloader(2);
}
public function testConstructorCallPathIsNotStringException() {
$this->expectException('Exception');
$notStringForPath = new stdClass();
new Myframework\Application\Autoloader\Autoloader(TEST_NAMESPACE, $notStringForPath);
}
public function testIsDirectoryExistsException() {
$this->expectException('Exception');
new Myframework\Application\Autoloader\Autoloader('x', 'Failed directory what not exist');
}
}
Test passed, and my methods are works, I am happy. But I doubt this is not how TDD works even if I follow every requirements.
My questions are:
- Is it ok to use constants in test what comes from
bootstrap.php
to define path? - All of the test ok, but is this the right way to test a constructor? I feel no for some reason, if its ok, please tell me, if not, please tell me why.
I found a lot of resources about TDD, videos, books, but testing the constructor is not in it.