Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Getting Composer and PHPUnit to autoload namespaces

Getting Composer and PHPUnit to autoload namespaces.

Overview

Details

Project Structure

ProjectRoot
 src
  ProjectName
   Subdir
    MyClass.php
 tests
  ProjectName
   Subdir
    MyClassTest.php

MyClass.php


<?php
namespace ProjectName\Subdir;

class MyClass {
    public function __construct(){

    }
}

MyClassTest.php

<?php

namespace ProjectName;

use ProjectName\Subdir\MyClass;

class MyClassTest extends \PHPUnit_Framework_TestCase {
    public function testInstance() {
        $myClass = new MyClass();
        $this->assertInstanceOf('ProjectName\Subdir\myClass', $myClass);
    }
}

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>

<phpunit bootstrap="vendor/autoload.php" colors="true">
    <testsuites>
        <testsuite name="ProjectRoot Test Suite">
            <directory>./tests/ProjectName</directory>
        </testsuite>
    </testsuites>
</phpunit>

composer.json

{
    "name": "garyrogers/projectname",
    "description": "description_text",
    "minimum-stability": "stable",
    "license": "proprietary",
    "authors": [
        {
            "name": "author's name",
            "email": "email@example.com"
        }
    ],
    "autoload": {
        "psr-0": {
            "ProjectName": "src"
        }
    },
    "require": {
        "monolog/monolog": "1.9.1"
    }
}

When updating the composer.json file be sure to run composer update to re-generate the autoload.php file that is referenced in the phpunit.xml file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.