Bel*_*len 5 php testing events functional-testing symfony4
我需要在 Symfony 4 中对订阅者进行功能测试,但我在寻找方法时遇到了问题。订阅者具有以下结构
/**
* Class ItemSubscriber
*/
class ItemSubscriber implements EventSubscriberInterface
{
/**
* @var CommandBus
*/
protected $commandBus;
/**
* Subscriber constructor.
*
* @param CommandBus $commandBus
*/
public function __construct(CommandBus $commandBus)
{
$this->commandBus = $commandBus;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
CommandFailedEvent::NAME => 'onCommandFailedEvent',
];
}
/**
* @param CommandFailedEvent $event
*
* @throws Exception
*/
public function onCommandFailedEvent(CommandFailedEvent $event)
{
$item = $event->getItem();
$this->processFailed($item);
}
/**
* Sends message
*
* @param array $item
*
* @throws Exception
*/
private function processFailed(array $item)
{
$this->commandBus->handle(new UpdateCommand($item));
}
}
Run Code Online (Sandbox Code Playgroud)
订阅者的流程是接收一个内部事件并通过rabbit通过命令总线向另一个项目发送消息。
我如何测试分派CommandFailedEvent该行中的事件processFailed(array $item)是否被执行?
有没有人有关于在 Symfony 4 中测试事件和订阅者的最佳实践的文档?
如果您想测试正在调用的命令总线处理程序的过程,您可以通过模拟期望测试依赖方法调用。PHPUnit 文档中有一些示例。
例如,你会有类似的东西:
$commandBus = $this->getMockBuilder(CommandBus::class)->disableOriginalConstructor()->getMock();
$commandBus->expects($this->once())->method('handle');
// Create your System Under Test
$SUT = new CommandFailedSubscriber($commandBus);
// Create event
$item = $this->getMockBuilder(YourItem::class)->getMock();
$event = new CommandFailedEvent($item);
// Dispatch your event
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber($SUT);
$dispatcher->dispatch($event);
Run Code Online (Sandbox Code Playgroud)
我希望这足以让您探索可能性并获得您的功能所需的覆盖范围。
祝你测试愉快!