-
Notifications
You must be signed in to change notification settings - Fork 4
/
MockObjectTest.php
113 lines (99 loc) · 2.55 KB
/
MockObjectTest.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
class MockObjectTest extends PHPUnit_Framework_TestCase
{
/**
* In this test the UsersView Mock Object checks
* that it is called the right number of times
*/
public function testPrintsOnlyActiveUsers()
{
$users = array(
new User('george', true),
new User('john', false),
new User('mark', false),
new User('joan', true),
new User('steve', false)
);
$view = $this->getMock('UsersView');
$view->expects($this->exactly(2))
->method('add');
$sut = new UsersController($users);
$sut->renderOn($view);
}
public function testUsersSelectUsersWhoseNameStartsWithAGivenPrefix()
{
$users = array(
new User('george', true),
$john = new User('john', true),
new User('mark', true),
new User('steve', true)
);
$view = $this->getMock('UsersView');
$view->expects($this->once())
->method('add')
->with($john);
$sut = new UsersController($users, 'j');
$sut->renderOn($view);
}
}
/**
* The interface the Mock Objects implement. The simpler this interface,
* the cleaner your code.
*/
interface UsersView
{
public function add(User $user);
}
/**
* The System Under Test. It should render on a View, which is substituted by
* a Test Double.
*/
class UsersController
{
private $users;
private $prefixFilter;
public function __construct(array $users, $prefixFilter = '')
{
$this->users = $users;
$this->prefixFilter = $prefixFilter;
}
public function renderOn(UsersView $view)
{
foreach ($this->users as $user)
{
if ($user->isActive() && $user->startsWith($this->prefixFilter)) {
$view->add($user);
}
}
}
}
/**
* In these tests the instances of User will actually be Dummy, which
* means just objects which are passed around without any method call
* is performed on them.
* This implementation is thus really brief.
*/
class User
{
private $name;
private $active;
public function __construct($name, $active)
{
$this->name = $name;
$this->active = $active;
}
public function isActive()
{
return $this->active;
}
public function startsWith($prefix)
{
if ($prefix == '') {
return true;
}
if (strstr($this->name, $prefix) == $this->name) {
return true;
}
return false;
}
}