Skip to content

Instantly share code, notes, and snippets.

@blackout314
Forked from GaryRogers/ComposerPHPUnit.md
Created February 23, 2017 21:06
Show Gist options
  • Save blackout314/c1af46fe89fc128c6e5e16bdf9107c39 to your computer and use it in GitHub Desktop.
Save blackout314/c1af46fe89fc128c6e5e16bdf9107c39 to your computer and use it in GitHub Desktop.
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