似乎很难,并且没有太多关于此的文档(我正在使用 FirendsOfBehat Symfony 扩展)。我想Transport
通过使用方法测试是否携带任何事件,get()
但我没有得到任何结果。感觉它没有路由正确的总线。
declare(strict_types=1);
namespace App\Features\BehatContext;
class MessengerContext implements Context
{
/**
* @var TransportInterface
*/
private $transport;
/**
* MessengerContext constructor.
*
* @param TransportInterface $transport ??? Is this ok
*/
public function __construct(TransportInterface $transport)
{
// Symfony\Component\Messenger\Transport\InMemoryTransport
$this->transport = $transport;
}
/**
* THIS IS WHAT DOESN'T WORK
* @Given /^(\d+) Events? "([^"]*)" is dispatched$/
*/
public function eventAEventIsDispatched()
{
$eventsDispatched = $this->transport->get();
Assert::assertTrue(count($eventsDispatched));
}
}
我的packages/messenger.yaml
配置:
framework:
messenger:
default_bus: event.bus
buses:
command.bus:
middleware:
- validation
event.bus:
default_middleware: allow_no_handlers
transports:
sync: 'sync://'
event: 'in-memory:///'
routing:
'App\AddMagazine': sync
'App\MagazineAdded': event
'App\EventAdapter': event
这是调度我的事件的类
declare(strict_types=1);
namespace App\Event\Dispatcher;
class SymfonyEventDispatcher implements ApplicationDomainDispatcherInterface
{
private $messageBus;
/**
* SymfonyEventDispatcher constructor.
*
* @param MessageBusInterface $sfDispatcher
*/
public function __construct(MessageBusInterface $eventBus)
{
// messageBus is Symfony\Component\Messenger\TraceableMessageBus
$this->messageBus = $eventBus;
}
/**
* @param EventInterface $event
*
* @return EventInterface
*/
public function dispatch(EventInterface $event): EventInterface
{
$eventAdapter = new EventAdapter($event);
$this->messageBus->dispatch(new Envelope($eventAdapter));
return $eventAdapter;
}
}
这是我的 service_test.yaml 文件,在运行 Behat 测试时会考虑该文件:
services:
_defaults:
autowire: true
autoconfigure: true
App\Features\BehatContext\:
resource: '../features/BehatContext/*'
App\Features\BehatContext\MessengerContext:
arguments:
$transport: '@messenger.transport.event'
检查我的日志,我可以看到信使确实发送了事件:
[2019-08-30 14:14:50] messenger.INFO: 使用 Symfony\Component\Messenger\Transport\InMemoryTransport 发送消息 App\EventAdapter {"message":"[object] (App\EventAdapter: {})", "类":"App\EventAdapter","sender":"Symfony\Component\Messenger\Transport\InMemoryTransport"} []