Skip to content

Instantly share code, notes, and snippets.

@GaryRogers
Last active May 15, 2023 16:01
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save GaryRogers/0fb41d649fa75d58eb8f to your computer and use it in GitHub Desktop.
Save GaryRogers/0fb41d649fa75d58eb8f 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