Mysterio4
Mysterio4

Reputation: 331

Unable to run PHPUnit Test with relative include path

I am doing an assignment and I was asked not to modify the Test File (CheckPayTest.php). I try to run test but phpunit cannot find the file and the file is correctly placed in the directory. Is it possible to make phpunit see this file when running the test

CheckPayTest.php

<?php declare(strict_types=1);

namespace cms\tests;

use PHPUnit\Framework\TestCase;

class CheckPayTest extends TestCase
{
    public function test_File_Read()
    {
        $readFile = include './../Creative.php';

        self::assertTrue($readFile);
    }
}

File to include Creative.php

<?php declare(strict_types=1);

namespace cms;

return true;

phpunit.xml Config

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="My Test Suite">
            <directory suffix="Test.php">tests</directory>
        </testsuite>
    </testsuites>
</phpunit>

Error

1) cms\tests\CheckPayTest::test_File_Read
include(./../Creative.php): failed to open stream: No such file or directory

Could this problem be solved without modifying CheckPayTest.php

Upvotes: 1

Views: 1628

Answers (1)

Jacek Dziurdzikowski
Jacek Dziurdzikowski

Reputation: 2265

Yes, you can make it run without modifying CheckPayTest.php.

Unfortunately someone who wrote this test was not aware of how php executable resolves relative directory paths - so the problem jumped out.

The solution is to change the directory from where php script starts to execute - php resolves relative paths from within any file during execution in reference to entry point of script start. The solution is to cd (change directory) to where this path './../Creative.php' becomes valid and run phpunit script from there.

Anyway, this solution is really poor - the correct way to fix it is to change first dot from the path to php magic constant __DIR__ which always provide absolute path to directory in which code was executed. I think you should change this file anyway - otherwise it will remain poorly written.

Try to change './../Creative.php' into __DIR__ . '/../Creative.php'

Upvotes: 3

Related Questions