Search code examples
namespacesphpunitphp-7autoload

phpunit Classes are not loaded in tests


I try to create my own library, with it's own namespace so it can be included in other projects.

I have done that and composer install runs without errors, but when I try to run my unit tests in my library it doesn't find any classes neither for mocking or for direct initialisation.

My folder structure is like this:

ProjectFolder
|
\_src
|    \_Sap
|         \_Classes
|
\_tests     
|     \_Sap
|         \_TestClasses  
|     bootstrap.php
\_vendor

The namespace used in classes follows this pattern:

namespace PuC\Sap;

The one used in the tests has this pattern:

namespace PuC\Sap\Tests\Sap;

My composer.json looks like this:

"autoload": {
    "psr-4": {
        "PuC\\Sap\\": "src/"
    }
},
"autoload-dev": {
    "psr-4": {
        "PuC\\Sap\\Tests\\": "tests/"
    }
},

In my tests folder I have added a bootstrap.php and refer to it in my phpunit.xml file:

<?php

$loader = @include __DIR__ . '/../vendor/autoload.php')
$loader->add('Sap', __DIR__);

No when I run this in the bash I get:

$ bin/phpunit tests/
PHPUnit 8.4.3 by Sebastian Bergmann and contributors.
......

7) PuC\Sap\Tests\Sap\HouseSoapServiceTest::testGetHouseData
Cannot stub or mock class or interface "PuC\Sap\Client\SapSoapClient" which does not exist

Same problem when I try to initialise the class directly.

Are my paths wrong? My namespaces?


Solution

  • The problem was the additional folder in my src folder. With this modified structure the tests are passing and the classes are found:

    ProjectFolder
    |
    \_src
    |    \_Classes
    |
    \_tests     
    |     \_Sap
    |         \_TestClasses  
    |     bootstrap.php
    \_vendor
    

    Thanks to Robbie Averill for pointing me in the right direction.