1
|
|
|
<?php namespace Unit\Chekote\Phake; |
2
|
|
|
|
3
|
|
|
use Phake\IMock; |
4
|
|
|
use Phake\Proxies\AnswerBinderProxy; |
5
|
|
|
use Phake\Proxies\StubberProxy; |
6
|
|
|
use Phake\Proxies\VerifierProxy; |
7
|
|
|
use Unit\Chekote\Phake\Exception\ExpectationException; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Combines a Phake Stubber and Verifier to create an expectation. |
11
|
|
|
* |
12
|
|
|
* This class is used to accomplish something similar to Prophecy predictions, but without the opinionated restrictions |
13
|
|
|
* that come with that mocking framework. |
14
|
|
|
*/ |
15
|
|
|
class Expectation |
16
|
|
|
{ |
17
|
|
|
/** the mock object */ |
18
|
|
|
protected IMock $mock; |
19
|
|
|
|
20
|
|
|
/** the method expected to be called */ |
21
|
|
|
protected string $method; |
22
|
|
|
|
23
|
|
|
/** the arguments expected to be passed to the method */ |
24
|
|
|
protected array $args; |
25
|
|
|
|
26
|
|
|
/** the number of times the method is expected to be called */ |
27
|
|
|
protected int $count; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Expectation constructor. |
31
|
|
|
* |
32
|
|
|
* @param IMock $mock the mock object |
33
|
|
|
* @param int $count number of times the method is expected to be called |
34
|
|
|
*/ |
35
|
|
|
public function __construct(IMock $mock, int $count) |
36
|
|
|
{ |
37
|
|
|
$this->mock = $mock; |
38
|
|
|
$this->count = $count; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Verifies that the expected method was called. |
43
|
|
|
* |
44
|
|
|
* @throws ExpectationException if a method has not been set for the expectation. |
45
|
|
|
* @throws ExpectationException if args have not been set for the expectation. |
46
|
|
|
* @return array|VerifierProxy |
47
|
|
|
*/ |
48
|
|
|
public function verify(): array|VerifierProxy |
49
|
|
|
{ |
50
|
|
|
if (!isset($this->method)) { |
51
|
|
|
throw new ExpectationException('Expectation method was not set'); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
if (!isset($this->args)) { |
55
|
|
|
throw new ExpectationException('Expectation args were not set'); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** @var VerifierProxy $verifier */ |
59
|
|
|
return Phake::verify($this->mock, Phake::times($this->count))->{$this->method}(...$this->args); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Sets the expected method to be called. |
64
|
|
|
* |
65
|
|
|
* @param string $method the method that is expected to be called. |
66
|
|
|
* @param array $args the args that are expected to be passed to the method. |
67
|
|
|
* |
68
|
|
|
* @return AnswerBinderProxy|StubberProxy |
69
|
|
|
*/ |
70
|
|
|
public function __call(string $method, array $args): AnswerBinderProxy|StubberProxy |
71
|
|
|
{ |
72
|
|
|
// record the method and args for verification later |
73
|
|
|
$this->method = $method; |
74
|
|
|
$this->args = $args; |
75
|
|
|
|
76
|
|
|
return Phake::when($this->mock)->$method(...$args); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|