通过具体 class 测试抽象 class

Test abstract class through concrete class

总的来说,我对 PHPSpec 和 BDD 真的很陌生,所以,也许我的假设不好,在那种情况下请纠正我。

让我们考虑一下这种情况

//src/myBundle/Model/FooInterface
interface FooInterface
{
    [...]
}

//src/myBundle/Model/FooAbstractManager
abstract class FooAbastractManager implements FooInterface
{
    public function aCommonMethodForAllConcrete()
    {
        [...]
    }
}

好吧,假设 aCommonMethodForAllConcrete() 与所有具体 class 共享一些实现,并且我只想编写一次测试用例。

我终于(如果我错了请纠正我)有一个 "idea":创建一个具体的 FooAbstractManager 仅用于测试这个通用方法并将所有具体方法测试留给具体 classes.

但是,因为我不希望这个 FooAbstractManager 成为我的 src 代码库的一部分,所以最好的情况是将 class 仅包含在spec 个文件夹。

问题:如何在不指定 ALL /src/myBundle/Model name-spaced files will be there 的情况下自定义该行为(因为,也许明天,我需要在此处保留一个具体的 class 文件)?

看看这个例子,它可以满足您的需要:https://github.com/Sylius/Translation/blob/master/spec/Model/AbstractTranslatableSpec.php

你是对的,你可以创建一个具体的 class 只是为了测试。它必须扩展抽象 class 并为抽象 class (如果有)的抽象方法提供虚拟实现。

因为这个为测试而创建的 class 只是摘要 class 的薄薄覆盖,它本身不提供任何功能,并且仅在单个 spec 你甚至不需要把它放到它自己的文件中。只需将其放在 spec 文件的末尾即可。

这是测试抽象 classes 的一种 "official" 方法。检查 phpspec 创作者之一在 this article 上的 "Limitation #5"。