简体   繁体   English

我需要在哪里放置 phpunit 的挂钩?

[英]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.我正在尝试模拟最终的 class,如果不做一些额外的工作,这通常是不可能的。 I've seen multiple options like implementing an interface and mocking that.我见过多种选择,例如实现接口和 mocking。 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.我找到的解决方案是 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.经过一番挖掘,我发现最好的方法是使用一个钩子并将其注册到 phpunit.xml 文件中。 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:并在 xml 文件中添加了所需的文本:

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

But everytime when I try to run the command "php./vendor/bin/phpunit".但是每次当我尝试运行命令“php./vendor/bin/phpunit”时。 I keep getting the same error "Class "BypassFinalHook" does not exist".我不断收到相同的错误“类“BypassFinalHook”不存在”。 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.我尝试通过在xml文件的扩展元素中添加文件参数来添加文件位置,但是它说它没有权限打开stream。所以我很茫然。 What do I need to do so that it finds the class?我需要做什么才能找到 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.目前,我只是把它放在根文件夹中,但我已经在多个位置尝试过它,结果仍然相同。

What worked for me is to put BypassFinalHook in tests\Hook\BypassFinalHook.php .对我有用的是将BypassFinalHook放在tests\Hook\BypassFinalHook.php中。

Add this namespace declaration to tests\Hook\BypassFinalHook.php将此命名空间声明添加到tests\Hook\BypassFinalHook.php

namespace tests\Hook;

Add this declaration to phpunit.xml :将此声明添加到phpunit.xml

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

This solved it for me.这为我解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM