简体   繁体   中英

PHP: Composer auto-load not working

Actually Iam new to PHP. I am running this from a nearly empty folder (actually following along a Lara-casts tutorial: Design a Fluent API with TDD).

My directory structure looks like

  • src
    • Expression.php
  • tests
    • ExpressionTest.php
  • vendor
  • composer.json
  • composer.lock

Inside composer.json:

{    
    "require-dev": {
        "phpunit/phpunit": "^5.2"
    },
    "autoload": {
        "psr-4": {
            "": "src/"
        }
    }
}

Inside ExpressionTest.php:

class ExpressionTest extends PHPUnit_Framework_TestCase
{
    /** @test */
    public function it_finds_a_string()
    {
        $regex = Expression::make()->find('www');

        $this->assertRegExp($regex, 'www');
    }
}

Inside Expression.php

<?php

class Expression
{

}

I then run composer dump-autoload and run phpunit but I still get:

 "Fatal error: Class 'Expression' not found in 
C:\Users\nobis\code\testing2\tests\ExpressionTest.php on line 8"

Is there something wrong with my syntax? My understanding of Composer is very basic. Thanks in advance.

You need to include the autoloader at the top of your test. It is typically at

require __DIR__ . '/vendor/autoload.php';

You can also add a phpunit.xml file to your tell it where the autoloader is then it will run it before every test:

<phpunit
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/5.2/phpunit.xsd"
    bootstrap="/path/to/bootstrap.php"

</phpunit>

PHPUnit does not know about Composer natively, therefore without configuring PHPUnit, it will not know about your autoloader setup.

try running PHPunit with --bootstrap vendor/autoload.php to tell it to load with your autoload file.

If that does not work, check your namespace value in your Composer configuration (ie "": "src/" might need to change.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM