/
Scenario.php
113 lines (95 loc) · 2.58 KB
/
Scenario.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/*
* This file is part of the broadway/broadway package.
*
* (c) Qandidate.com <opensource@qandidate.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Broadway\CommandHandling\Testing;
use Broadway\CommandHandling\CommandHandler;
use Broadway\Domain\DomainEventStream;
use Broadway\Domain\DomainMessage;
use Broadway\Domain\Metadata;
use Broadway\EventStore\TraceableEventStore;
use PHPUnit_Framework_TestCase;
/**
* Helper testing scenario to test command handlers.
*
* The scenario will help with testing command handlers. A scenario consists of
* three steps:
*
* 1) given(): Load a history of events in the event store
* 2) when(): Dispatch a command
* 3) then(): events that should have been persisted
*/
class Scenario
{
private $eventStore;
private $commandHandler;
private $testCase;
private $aggregateId;
public function __construct(
PHPUnit_Framework_TestCase $testCase,
TraceableEventStore $eventStore,
CommandHandler $commandHandler
) {
$this->testCase = $testCase;
$this->eventStore = $eventStore;
$this->commandHandler = $commandHandler;
$this->aggregateId = '1';
}
/**
* @param string $aggregateId
*
* @return Scenario
*/
public function withAggregateId(string $aggregateId): Scenario
{
$this->aggregateId = $aggregateId;
return $this;
}
/**
* @param array $events
*
* @return Scenario
*/
public function given(array $events = null): Scenario
{
if ($events === null) {
return $this;
}
$messages = [];
$playhead = -1;
foreach ($events as $event) {
$playhead++;
$messages[] = DomainMessage::recordNow($this->aggregateId, $playhead, new Metadata([]), $event);
}
$this->eventStore->append($this->aggregateId, new DomainEventStream($messages));
return $this;
}
/**
* @param mixed $command
*
* @return Scenario
*/
public function when($command): Scenario
{
$this->eventStore->trace();
$this->commandHandler->handle($command);
return $this;
}
/**
* @param array $events
*
* @return Scenario
*/
public function then(array $events): Scenario
{
$this->testCase->assertEquals($events, $this->eventStore->getEvents());
$this->eventStore->clearEvents();
return $this;
}
}