代码之家  ›  专栏  ›  技术社区  ›  naspy971

如何在phpunit中使用mock或force参数值来修改setter行为?

  •  0
  • naspy971  · 技术社区  · 2 年前

    我真的不确定我需要做的事情是否可能,但也许我会感到惊讶。。。

    上下文:我正在测试调用方法的API 'createAttachment' 以下为:

    public function createAttachment(string $type, int $id, UploadedFile $file)
        {
             // stuff
             $attachment = new Attachment();
             $attachment->setPath($uploadDir . DIRECTORY_SEPARATOR . $filenamePath);
             // stuff
             $this->em->persist($attachment);
             $this->em->flush();
        }
    

    当前动态创建的路径 setPath() 不适合我的测试,因为它会在我不希望创建它的地方创建一个文件。

    所以我需要确保 设置路径() 将始终将我想要的值设置为$path属性,这样当保存$attachment时,文件的位置就是我想要的位置。

    这里的一个大问题可能是 Attachment 未传递给 createAttachment 使用DI,但它是在方法内部实例化的,所以很可能它甚至不是“可模拟的”。

    下面是附件实体的一个潜标:

    class Attachment {
    
        private ?string $path;
    
        public function setPath(?string $path): self
            {
                $this->path = $path;
        
                return $this;
            }
    
    0 回复  |  直到 2 年前
        1
  •  1
  •   Bademeister    2 年前

    在我们聊天的背景下。我认为这就是反思的样子。最重要的是,您可以单独测试UploadPathBuilder。对于UploadedFile,您可以创建一个Mock。

    interface UploadPathBulderInterface
    {
        public function getPath(): string;
    }
    
    
    class UploadPathBuilder implements UploadPathBulderInterface
    {
        private UploadedFile $file;
    
        /**
         * @param UploadedFile $file
         */
        public function __construct(UploadedFile $file)
        {
            $this->file = $file;
        }
    
        public function getPath(): string
        {
            // stuff
            return $uploadDir . DIRECTORY_SEPARATOR . $filenamePath;
        }
    }
    
    
    class TestUploadPathBuilder implements UploadPathBulderInterface
    {
        public function getPath(): string {
            return "/my/path/for/testing";
        }
    }
    
    class FooBar 
    {
        public function createAttachment(string $type, int $id, UploadPathBulderInterface $pathBulder)
        {
            // stuff
            $attachment = new Attachment();
            $attachment->setPath($pathBulder->getPath());
            // stuff
            $this->em->persist($attachment);
            $this->em->flush();
        }
    }
    
    

    实施申请

    
    $fooBar = new FooBar();
    $fooBar->createAttachment(
        "string",
        1234,
        new UploadPathBuilder($file);
    );
    
    

    实施测试

    $fooBar = new FooBar();
    $fooBar->createAttachment(
        "string",
        1234,
        new TestUploadPathBuilder();
    );