'Where do I need to place a hook for phpunit?

The answer is probably very simple, but I've been running around in circles and I can't find an answer anywhere. I'm trying to mock a final class which is normally not possible without doing some extra work. I've seen multiple options like implementing an interface and mocking that. But that would create extra work for nothing so I searched for a way to bypass the problem. The solution I found was dg/bypass-finals. I only needed to do 1 thing to implement it. Execute this line of code as early ass possible:

DG\BypassFinals::enable();

After some digging I found out the best way to do this is by using a hook and registering this in the phpunit.xml file. So I created my hook that looks like this:

<?php declare(strict_types=1);
use DG\BypassFinals;
use PHPUnit\Runner\BeforeTestHook;

final class BypassFinalHook implements BeforeTestHook
{
   public function executeBeforeTest(string $test): void
   {
       BypassFinals::enable();
   }
}

And added the required text in the xml file:

<phpunit bootstrap="vendor/autoload.php">
   <extensions>
      <extension class="BypassFinalHook"/>
   </extensions>
</phpunit>

But everytime when I try to run the command "php ./vendor/bin/phpunit". I keep getting the same error "Class "BypassFinalHook" does not exist". I tried adding the file location by adding the file parameter in the extension element of the xml file, but then it said it didn't have the permissions to open the stream. So I'm at a loss. What do I need to do so that it finds the class? Does it require to be saved at a certain location? Currently, I just have it in the root folder, but I've tried it in multiple locations and still the same result.



Solution 1:[1]

What worked for me is to put BypassFinalHook in tests\Hook\BypassFinalHook.php.

Add this namespace declaration to tests\Hook\BypassFinalHook.php

namespace tests\Hook;

Add this declaration to phpunit.xml:

<extensions>
    <extension class="Tests\Hook\BypassFinalHook"/>
</extensions>

This solved it for me.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeroen Huinink