|
3 | 3 | namespace EasyMock; |
4 | 4 |
|
5 | 5 | use PHPUnit_Framework_MockObject_Generator; |
6 | | -use PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount; |
| 6 | +use PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount as AnyInvokedCount; |
| 7 | +use PHPUnit_Framework_MockObject_Matcher_Invocation as InvocationMatcher; |
| 8 | +use PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastOnce as InvokedAtLeastOnce; |
7 | 9 | use PHPUnit_Framework_MockObject_MockObject as MockObject; |
8 | 10 |
|
9 | 11 | /** |
@@ -33,15 +35,43 @@ public static function mock($classname, array $methods = array()) |
33 | 35 | } |
34 | 36 |
|
35 | 37 | foreach ($methods as $method => $return) { |
36 | | - self::mockMethod($mock, $method, $return); |
| 38 | + self::mockMethod($mock, $method, new AnyInvokedCount, $return); |
37 | 39 | } |
38 | 40 |
|
39 | 41 | return $mock; |
40 | 42 | } |
41 | 43 |
|
42 | | - private static function mockMethod(MockObject $mock, $method, $return) |
| 44 | + /** |
| 45 | + * Mock the given class by spying on method calls. |
| 46 | + * |
| 47 | + * This is the same as EasyMock::mock() except this assert that methods are called at |
| 48 | + * least once. |
| 49 | + * |
| 50 | + * @see mock() |
| 51 | + * |
| 52 | + * @param string $classname The class to mock. Can also be an existing mock to mock new methods. |
| 53 | + * @param array $methods Array of values to return, indexed by the method name. |
| 54 | + * |
| 55 | + * @return \PHPUnit_Framework_MockObject_MockObject |
| 56 | + */ |
| 57 | + public static function spy($classname, array $methods = array()) |
| 58 | + { |
| 59 | + if ($classname instanceof MockObject) { |
| 60 | + $mock = $classname; |
| 61 | + } else { |
| 62 | + $mock = self::createMock($classname); |
| 63 | + } |
| 64 | + |
| 65 | + foreach ($methods as $method => $return) { |
| 66 | + self::mockMethod($mock, $method, new InvokedAtLeastOnce, $return); |
| 67 | + } |
| 68 | + |
| 69 | + return $mock; |
| 70 | + } |
| 71 | + |
| 72 | + private static function mockMethod(MockObject $mock, $method, InvocationMatcher $invocation, $return) |
43 | 73 | { |
44 | | - $methodAssertion = $mock->expects(new PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount) |
| 74 | + $methodAssertion = $mock->expects($invocation) |
45 | 75 | ->method($method); |
46 | 76 |
|
47 | 77 | if (is_callable($return)) { |
|
0 commit comments