-
Notifications
You must be signed in to change notification settings - Fork 4
/
FakeObjectTest.php
102 lines (91 loc) · 2.3 KB
/
FakeObjectTest.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
<?php
/**
* The System Under Test should use this database-related class to move Posts around.
* However we inject a FakePostDao in order to avoid using a real database in this test,
* and at the same time better define the interface between the two.
*/
class FakeObjectTest extends PHPUnit_Framework_TestCase
{
public function testMergesTwoThreads()
{
$dao = new FakePostDao(array(
1 => array(
new Post('Hello'),
new Post('Hello!'),
new Post('')
),
2 => array(
new Post('Hi'),
new Post('Hi!')
),
3 => array(
new Post('Good morning.')
)
));
$forumManager = new ForumManager($dao);
$forumManager->mergeThreadsByIds(1, 2);
$thread = $dao->getThread(1);
$this->assertEquals(5, count($thread));
}
}
/**
* The SUT.
*/
class ForumManager
{
private $dao;
public function __construct(PostsDao $dao)
{
$this->dao = $dao;
}
public function mergeThreadsByIds($originalId, $toBeMergedId)
{
$original = $this->dao->getThread($originalId);
$toBeMerged = $this->dao->getThread($toBeMergedId);
$newOne = array_merge($original, $toBeMerged);
$this->dao->removeThread($originalId);
$this->dao->removeThread($toBeMergedId);
$this->dao->addThread($originalId, $newOne);
}
}
/**
* Interface for the collaborator to substitute with the Test Double.
*/
interface PostsDao
{
public function getThread($id);
public function removeThread($id);
public function addThread($id, array $thread);
}
/**
* Fake implementation.
*/
class FakePostDao implements PostsDao
{
private $threads;
public function __construct(array $initialState)
{
$this->threads = $initialState;
}
public function getThread($id)
{
return $this->threads[$id];
}
public function removeThread($id)
{
unset($this->threads[$id]);
}
/**
* We model Thread as array of Posts for simplicity.
*/
public function addThread($id, array $thread)
{
$this->threads[$id] = $thread;
}
}
/**
* Again a Dummy object: minimal implementation, to make this test pass.
*/
class Post
{
}