【问题标题】:How do i test a method of class that execute an method with an anonymous function as arguments?如何测试以匿名函数作为参数执行方法的类方法?
【发布时间】:2020-06-05 00:50:05
【问题描述】:

对于特定需求,我必须在 symfony 4.4 项目中测试Kernel 类,除了registerContainerConfiguration() 下的方法外,一切都很好。它只包含一个将参数作为Anonymous function 的方法,我怎么能完全测试它?我找不到办法进去。

public function registerContainerConfiguration(LoaderInterface $loader)
{
    $loader->load(function (ContainerBuilder $container) use ($loader) {
        $container->loadFromExtension('framework', [
            'router' => [
                'resource' => 'kernel::loadRoutes',
                'type' => 'service',
            ],
        ]);

        if (!$container->hasDefinition('kernel')) {
            $container->register('kernel', static::class)
                ->setSynthetic(true)
                ->setPublic(true)
            ;
        }

        $kernelDefinition = $container->getDefinition('kernel');
        $kernelDefinition->addTag('routing.route_loader');

        if ($this instanceof EventSubscriberInterface) {
            $kernelDefinition->addTag('kernel.event_subscriber');
        }

        $this->configureContainer($container, $loader);

        $container->addObjectResource($this);
    });
}

我已经写的代码:

public function testRegisterContainerConfiguration(): void
{
    $loader = $this->prophesize(LoaderInterface::class);

    $loader->load()
        ->shouldBeCalledOnce() // here i'm stuck
    ;

    $this->kernel->registerContainerConfiguration($loader->reveal());
}

PS:我试过this one,但它似乎只模拟匿名函数。

【问题讨论】:

    标签: php symfony phpunit


    【解决方案1】:

    一个想法是在测试目录中创建真正的加载器类用于测试目的,例如:

    class LoaderMockObject implements LoaderInterface {
        //...
    
        public function __construct(ContainerBuilder $containerBuilder)
        {
            $this->containerBuilder = $containerBuilder;
        }
    
        public function load($resource, $type = null)
        {
            return $resource($this->containerBuilder);
        }
    
        // ...
    }
    

    然后您可以通过这种方式轻松测试containerBuilder 行为:

    public function testRegisterContainerConfiguration()
        {
            $containerBuilder = $this->createMock(ContainerBuilder::class);
    
            $containerBuilder->expects($this->once())
                ->method('loadFromExtension')
                ->withAnyParameters();
    
            // other expectations
    
            $loaderMock = new LoaderMockObject($containerBuilder);
            $kernel = new Kernel('test', false);
    
            $kernel->registerContainerConfiguration($loaderMock);
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-30
      • 2010-11-03
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-02
      相关资源
      最近更新 更多