【问题标题】:Testing objects that are usually generated by factories with phpspec使用 phpspec 测试通常由工厂生成的对象
【发布时间】:2016-01-23 03:26:52
【问题描述】:

如何实施可以利用工厂创建测试对象的测试?

例如,假设您有这样的 Zend Framework 2 工厂:

class FooServiceFactory implements FactoryInterface{

    public function createService( ServiceLocatorInterface $serviceLocator ){

        $bar = new Bar($serviceLocator->get('config'));
        return new FooService( $bar );
    }
}

我可以轻松地将我的 FooServiceSpec 的 let 函数修改为如下所示(使用 my ZF2 phpspec extension to get the SM):

function let(){
    $bar = new Bar($this->getServiceLocator()->get('config'));
    $this->beConstructedWith( $bar );
}

但是,我这样做并不是在测试我的工厂。我当然可以编写单独的测试来测试工厂本身,但这是重复的工作。

有没有办法将对象实例化完全推迟到自定义例程?这样在我的测试中,我可以做到(虚构):

function letBetter(){
    return $this->getServiceLocator()->get(FooService::class);
}

尽量避免重复!

谢谢!!

【问题讨论】:

    标签: php zend-framework2 phpspec


    【解决方案1】:

    如果您正在测试您的 FooService 对象,您应该只测试 FooService 对象并模拟其他所有内容(您不应在规范中使用任何服务定位器单元):

    class FooServiceSpec extends ObjectBehaviour
    {
        function let(Bar $bar)
        {
            $this->beConstructedWith($bar);
        }
    
        function it_xxx()
        {
            // ...
        }
    }
    

    如果您想测试工厂,请仅测试工厂而不是服务定位器或FooService

    【讨论】:

    • 此外,您应该为您的工厂编写一个单独的集成测试,以确保它确实做到了它所承诺的并创建了一个 FooService。您不会为此使用 phpspec,但例如 phpunit。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多