I'm trying to use PHPUnit in a PHP project. Here is my project structure (files are in italic font style)
controllers
tests
vendor
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()
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.
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>
Try composer dump-autoload -o
command
Call phpunit
from the root folder:
$ cd C:\xampp\htdocs\PHPUnitTestProject\
$ vendor\bin\phpunit tests/PagesTest.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With