我需要在 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));
}
}
订阅者的流程是接收一个内部事件并通过rabbit通过命令总线向另一个项目发送消息。
我如何测试调度事件
CommandFailedEvent
processFailed(array $item)
中的线路被执行?有没有人有关于在 Symfony 4 中测试事件和订阅者的最佳实践的文档?
最佳答案
如果你想测试正在调用的命令总线处理程序的过程,你可以测试依赖方法调用,感谢 mock expects .您在 PHPUnit documentation 中有一些示例.
例如,你会有类似的东西:
$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);
我希望这足以让您探索可能性并获得您的功能所需的覆盖范围。
祝你测试愉快!
关于php - Symfony 4 中的功能测试事件和订阅者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60541522/