Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Fatal error: Class not found - PHPUnit

Tags:

I'm trying to use PHPUnit in a PHP project. Here is my project structure (files are in italic font style)

  • controllers

    • Pages.php
  • tests

    • pagesTest.php
  • vendor

    • bin
      • phpunit.bat
  • composer.json

My files:

composer.json

{
    "require-dev": {
        "phpunit/phpunit":"5.5.4"
    }
}

Pages.php

<?php
namespace controllers

class Pages
{
    public function render()
    {
        return 'Hello World';
    }

}

pagesTest.php

<?php

class PagesTest extends PHPUnit_Framework_TestCase
{
    public function testRenderReturnsHelloWorld()
    {
        $pages = new \controllers\Pages();
        $expected = 'Hello Word';
        $this->assertEquals($expected, $pages->render());
    }
}

When I open the command line I write:

C:\xampp\htdocs\PHPUnitTestProject\vendor\bin>phpunit ../../tests/PagesTest.php

I receive this error message: PHP Fatal error: Class 'controllers\Pages' not found in C:\xampp\htdocs\PHPUnitTestProject\tests\pagesTest.php on line 7

It's a path problem. I think it's because it searches for C:\xampp\htdocs\PHPUnitTestProject\vendor\bin\controllers\Pages() which doesn't exists.
It should be C:\xampp\htdocs\PHPUnitTestProject\controllers\Pages()

like image 407
splunk Avatar asked Sep 12 '16 15:09

splunk


4 Answers

You need to point to the tested class, so in pagesTest.php add a require:

require __DIR__ . "/../controllers/Pages.php";

Or if you are using autoloading, then you can bootstrap the autoload in your command line

phpunit --bootstrap src/autoload.php

Or you can set up a phpunit.xml configuration file like this example (from the PHPUnit page I linked to above):

<phpunit bootstrap="src/autoload.php">
  <testsuites>
    <testsuite name="money">
      <directory>tests</directory>
    </testsuite>
  </testsuites>
</phpunit>

Which you then use with the --configuration option.

like image 75
Katie Avatar answered Oct 06 '22 00:10

Katie


Adding bootstrap="vendor/autoload.php" in phpunit.xml.dist solved the issue for me.

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"> <!-- in here -->
    <php>
        <!-- ... -->
    </php>
    <testsuites>
       <!-- ... -->
    </testsuites>
</phpunit>
like image 21
Allen Avatar answered Oct 05 '22 22:10

Allen


Try composer dump-autoload -o command

like image 36
rosell.dk Avatar answered Oct 05 '22 22:10

rosell.dk


Call phpunit from the root folder:

$ cd C:\xampp\htdocs\PHPUnitTestProject\
$ vendor\bin\phpunit tests/PagesTest.php
like image 35
JorgeObregon Avatar answered Oct 06 '22 00:10

JorgeObregon