0
votes

So I installed phpunit globally using composer. But I want to use it in a project that also uses composer, but doesn't have phpunit installed (the reasons for this are boring).

So I run the first test below and get the error.

Fatal error: Class 'PHPUnit\Framework\TestCase' not found in /vagrant/sites/core/trunk/Notify/php/tests/MyFirstTest.php on line 5

I thought that loading the global composer autoloader would let phpunit look in the global composer directory for the phpunit classes but it doesn't seem to be able to find it. I guess it's setting $vendorDir (below) to the local composer directory instead of the global one. Is there a way to make it check both?

Here's the line from /home/vagrant/.composer/vendor/composer/autoload_classmap.php that shows the class is in the global autoload classmap.

'PHPUnit_Framework_TestCase' => $vendorDir . '/phpunit/phpunit/src/Framework/TestCase.php',

Here's the command line I'm using to start the process.

phpunit --bootstrap tests/bootstrap.php tests/MyFirstTest.php

Here's MyFirstTest.php

<?php

use PHPUnit\Framework\TestCase;

class MyFirstTest extends TestCase {
    public function testOneIsOne() {
        $this->assertEquals(1, 1); 
    }   
}

Here's bootstrap.php where I load the global phpunit autoloader.

<?php

require_once('/home/vagrant/.composer/vendor/autoload.php');

Writing out this question has helped to clarify my thoughts a lot. If anyone's got a nice solution that'd be great. I'm starting to think I should just install phpunit locally.

Cheers for any advice.

1
I can't think of any good reason for not adding phpunit to the require-dev section of your composer.lock file. Just install it for your project.Bartosz Zasada

1 Answers

0
votes

The problem was that I was using PhpUnit 4.8 because the project I'm working on uses php 5.5.9 and the current version of PhpUnit, 5.0 and above requires php 5.6.0.

The tutorial on phpunit.de/getting-started.html is for PhpUnit 5.0 and above. It looks like PhpUnit 5.0 introduced namespacing to the framework. Before that the PHPUnit\Framework\TestCase class I was trying to load was PHPUnit_Framework_TestCase instead.

You can actually see that in the line from the classmap file:

'PHPUnit_Framework_TestCase' => $vendorDir . '/phpunit/phpunit/src/Framework/TestCase.php',

But I thought the underscores in the name of the class were just some name wrangling composer's classmap was doing to represent the namespacing.

As soon as I changed MyFirstTest.php to look for the right class PhpUnit_Framework_TestCase and dropped the use statement everything worked fine. There was no need to install PhpUnit locally. It found the proper class in the global composer vendor directory.

<?php

class MyFirstTest extends PhpUnit_Framework_TestCase {
    public function testOneIsOne() {
        $this->assertEquals(1, 1); 
    }   
}