-
Notifications
You must be signed in to change notification settings - Fork 3
/
MockBuilder.php
521 lines (456 loc) · 13 KB
/
MockBuilder.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
<?php
namespace Concise\Mock;
use Concise\Services\MethodArguments;
use Concise\TestCase;
use Concise\Services\NumberToTimesConverter;
use Concise\Services\ValueRenderer;
use InvalidArgumentException;
use Exception;
use ReflectionClass;
use Closure;
use Concise\Validation\ArgumentChecker;
use ReflectionException;
use ReflectionMethod;
class MockBuilder
{
/**
* @var TestCase
*/
protected $testCase;
/**
* @var array
*/
protected $rules = array();
/**
* @var bool
*/
protected $niceMock;
/**
* The names of the methods to be mocked.
* @var array
*/
protected $mockedMethods = array();
/**
* The original fully-qualified class name to create the mock from.
* @var string
*/
protected $className;
/**
* Used internally as the active mocked method when using chained methods to builds the rules
* for this method.
* @var array
*/
protected $currentRules = array();
/**
* The arguments associated with this rule.
* @var array
*/
protected $currentWith = null;
/**
* Constructor arguments.
* @var array
*/
protected $constructorArgs;
/**
* @var boolean
*/
protected $disableConstructor = false;
/**
* A list of methods that should be exposed as public.
* @var array
*/
protected $expose = array();
/**
* If the current rule is expect()
* @var boolean
*/
protected $isExpecting = false;
/**
* You may set a customer class name for this mock.
* @var string
*/
protected $customClassName = '';
/**
* @var object|null
*/
protected $objectState;
/**
* @param TestCase $testCase
* @param string $className
* @param bool $niceMock
* @param array $constructorArgs
* @throws \Exception
*/
public function __construct(TestCase $testCase, $className, $niceMock,
array $constructorArgs = array())
{
ArgumentChecker::check($className, 'string', 2);
ArgumentChecker::check($niceMock, 'bool', 3);
$this->testCase = $testCase;
if (!class_exists($className) && !interface_exists($className)) {
throw new Exception("Class or interface '$className' does not exist.");
}
$this->className = $className;
$this->niceMock = $niceMock;
$this->constructorArgs = $constructorArgs;
}
/**
* @param array $methods
* @param Action\AbstractAction $action
* @param integer $times
*/
protected function addRule(array $methods, Action\AbstractAction $action, $times = -1)
{
$this->currentRules = $methods;
foreach ($methods as $method) {
$this->mockedMethods[] = $method;
$this->rules[$method] = array();
}
$this->setupWith($action, $times);
}
protected function reset()
{
$this->currentWith = null;
$this->isExpecting = false;
}
/**
* @param array|string $arg
* @throws \Exception
* @return MockBuilder
*/
public function stub($arg)
{
$this->reset();
if (is_array($arg)) {
if (count($arg) === 0) {
throw new Exception("stub() called with array must have at least 1 element.");
}
foreach ($arg as $method => $value) {
$this->addRule(array($method), new Action\ReturnValueAction(array($value)));
}
} else {
$this->addRule(func_get_args(), new Action\ReturnValueAction(array(null)));
}
return $this;
}
protected function restoreState($mockInstance)
{
if (null !== $this->objectState) {
$reflection = new ReflectionClass($this->objectState);
foreach ($reflection->getProperties() as $property) {
$property->setAccessible(true);
$name = $property->getName();
$value = $property->getValue($this->objectState);
$originalReflection = new ReflectionClass($this->className);
$originalProperty = $originalReflection->getProperty($name);
$originalProperty->setAccessible(true);
$originalProperty->setValue($mockInstance, $value);
}
}
}
/**
* Compiler the mock into a usable instance.
* @return object
*/
public function get()
{
$compiler = new ClassCompiler($this->className, $this->niceMock, $this->constructorArgs,
$this->disableConstructor);
if ($this->customClassName) {
$compiler->setCustomClassName($this->customClassName);
}
$compiler->setRules($this->rules);
foreach ($this->expose as $method) {
$compiler->addExpose($method);
}
$mockInstance = $compiler->newInstance();
$this->testCase->addMockInstance($this, $mockInstance);
$this->restoreState($mockInstance);
return $mockInstance;
}
/**
* @return string
*/
protected function getWithKey()
{
return md5(json_encode($this->currentWith));
}
/**
* @return boolean
*/
protected function hasAction($rule)
{
$action = $this->rules[$rule][$this->getWithKey()]['action'];
if ($action instanceof Action\ReturnValueAction && is_null(current($action->getValue()))) {
return false;
}
return true;
}
/**
* @param Action\AbstractAction $action
* @throws \Exception
* @return MockBuilder
*/
protected function setAction(Action\AbstractAction $action)
{
foreach ($this->currentRules as $rule) {
if ($this->methodIsNeverExpected($rule)) {
$message = "You cannot assign an action to '{$rule}()' when it is never expected.";
throw new Exception($message);
}
if ($this->hasAction($rule)) {
throw new Exception("{$rule}() has more than one action attached.");
}
$this->rules[$rule][$this->getWithKey()]['action'] = $action;
}
return $this;
}
/**
* @param string $rule
* @return bool
*/
protected function methodIsNeverExpected($rule)
{
return $this->rules[$rule][$this->getWithKey()]['times'] === 0;
}
/**
* @throws \Exception
* @return MockBuilder
*/
public function andReturn()
{
return $this->setAction(new Action\ReturnValueAction(func_get_args()));
}
/**
* @param \Exception $exception
* @return MockBuilder
*/
public function andThrow(Exception $exception)
{
return $this->setAction(new Action\ThrowAction($exception));
}
/**
* Expect the method to called called exactly once.
* @return MockBuilder
*/
public function once()
{
return $this->exactly(1);
}
/**
* @param string $method
* @return MockBuilder
*/
public function expect($method)
{
ArgumentChecker::check($method, 'string');
$this->reset();
$this->isExpecting = true;
$this->addRule(func_get_args(), new Action\ReturnValueAction(array(null)));
$this->once();
foreach (func_get_args() as $method) {
$this->rules[$method][$this->getWithKey()]['hasSetTimes'] = false;
}
return $this;
}
/**
* @return MockBuilder
*/
public function expects()
{
return call_user_func_array(array($this, 'expect'), func_get_args());
}
/**
* Expect the method to be called exactly twice.
* @return MockBuilder
*/
public function twice()
{
return $this->exactly(2);
}
/**
* Expect that the method is never called.
* @return MockBuilder
*/
public function never()
{
return $this->exactly(0);
}
/**
* @param integer $times
* @return MockBuilder
*/
public function exactly($times)
{
ArgumentChecker::check($times, 'integer');
foreach ($this->currentRules as $rule) {
$this->rules[$rule][$this->getWithKey()]['hasSetTimes'] = true;
$this->rules[$rule][$this->getWithKey()]['times'] = $times;
}
return $this;
}
/**
* @param integer $times
*/
protected function setupWith(Action\AbstractAction $action, $times)
{
foreach ($this->currentRules as $rule) {
$this->rules[$rule][$this->getWithKey()] = array(
'action' => $action,
'times' => $times,
'with' => $this->currentWith,
'hasSetTimes' => false,
);
}
}
/**
* Expected arguments when invoking the mock.
* @throws \Exception
* @return MockBuilder
*/
public function with()
{
$methodArguments = new MethodArguments();
$this->currentWith = $methodArguments->getMethodArgumentValues(func_get_args(), $this->getClassName() . "::" . $this->currentRules[0]);
foreach ($this->currentRules as $rule) {
if ($this->rules[$rule][md5('null')]['hasSetTimes']) {
$renderer = new ValueRenderer();
$converter = new NumberToTimesConverter();
$args = $renderer->renderAll($this->currentWith);
$times = $this->rules[$rule][md5('null')]['times'];
$convertToMethod = $converter->convertToMethod($times);
throw new Exception(sprintf("%s:\n ->expects('%s')->with(%s)->%s",
"When using with you must specify expectations for each with()",
$rule, $args, $convertToMethod));
}
$this->rules[$rule][md5('null')]['times'] = -1;
}
$this->setupWith(new Action\ReturnValueAction(array(null)), $this->isExpecting ? 1 : -1);
return $this;
}
/**
* @return array
*/
public function getRules()
{
return $this->rules;
}
/**
* @return bool
*/
protected function isInterface()
{
$refClass = new ReflectionClass($this->className);
return $refClass->isInterface();
}
/**
* @return bool
*/
protected function isPartialMock()
{
return null !== $this->objectState;
}
/**
* @throws InvalidArgumentException
* @return MockBuilder
*/
public function disableConstructor()
{
if ($this->isInterface()) {
$message = "You cannot disable the constructor of an interface ({$this->className}).";
throw new InvalidArgumentException($message);
}
if ($this->isPartialMock()) {
throw new Exception("You cannot disable the constructor on a partial mock because any constructor would have already run ({$this->className}).");
}
$this->disableConstructor = true;
return $this;
}
/**
* @param string ... A list of methods to expose.
* @return $this
*/
public function expose()
{
if (!$this->niceMock) {
throw new Exception("You cannot expose a method on a mock that is not nice.");
}
foreach (func_get_args() as $arg) {
if (!is_array($arg)) {
$arg = array($arg);
}
$this->expose = array_merge($arg, $this->expose);
}
return $this;
}
/**
* @return MockBuilder
*/
public function andReturnSelf()
{
return $this->setAction(new Action\ReturnSelfAction());
}
/**
* @param Closure $action
* @return MockBuilder
* @throws Exception
*/
public function andDo(Closure $action)
{
return $this->setAction(new Action\DoAction($action));
}
/**
* @param string $customClassName
* @return $this
*/
public function setCustomClassName($customClassName)
{
ArgumentChecker::check($customClassName, 'string');
$this->customClassName = $customClassName;
return $this;
}
/**
* @param Closure $returnCallback
* @return MockBuilder
* @throws Exception
*/
public function andReturnCallback(Closure $returnCallback)
{
return $this->setAction(new Action\ReturnCallbackAction($returnCallback));
}
/**
* @param string $property
* @throws InvalidArgumentException
* @return MockBuilder
*/
public function andReturnProperty($property)
{
ArgumentChecker::check($property, 'string');
if ($this->isInterface()) {
$message = "You cannot return a property from an interface ({$this->className}).";
throw new InvalidArgumentException($message);
}
return $this->setAction(new Action\ReturnPropertyAction($property));
}
/**
* @param object $objectState
*/
public function setObjectState($objectState)
{
$this->objectState = $objectState;
}
/**
* @return string
*/
public function getClassName()
{
return $this->className;
}
/**
* @return MockBuilder
*/
public function exposeAll()
{
return $this;
}
}