From 9710e1707ba0563071c8caf327a4867f18a907ee Mon Sep 17 00:00:00 2001 From: Matthieu Napoli Date: Fri, 16 Jan 2015 17:26:24 +1300 Subject: [PATCH] Support for throwing exception --- README.md | 8 ++++++++ src/EasyMock.php | 2 ++ tests/Fixture/CustomException.php | 7 +++++++ tests/MockClassTest.php | 26 ++++++++++++++++++++++---- 4 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 tests/Fixture/CustomException.php diff --git a/README.md b/README.md index 01619f5..2c49fad 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,14 @@ $mock = EasyMock::mock('My\Class', array( )); ``` +You can also have methods throw exceptions by providing an `Exception` instance: + +```php +$mock = EasyMock::mock('My\Class', array( + 'sayHello' => new \RuntimeException('Whoops'), +)); +``` + ### What if? If you want to use assertions or other PHPUnit features, just do it: diff --git a/src/EasyMock.php b/src/EasyMock.php index bfeeee7..3a40bd8 100644 --- a/src/EasyMock.php +++ b/src/EasyMock.php @@ -51,6 +51,8 @@ private static function mockMethod(PHPUnit_Framework_MockObject_MockObject $mock if (is_callable($return)) { $methodAssertion->willReturnCallback($return); + } elseif ($return instanceof \Exception) { + $methodAssertion->willThrowException($return); } else { $methodAssertion->willReturn($return); } diff --git a/tests/Fixture/CustomException.php b/tests/Fixture/CustomException.php new file mode 100644 index 0000000..62b65b7 --- /dev/null +++ b/tests/Fixture/CustomException.php @@ -0,0 +1,7 @@ + @@ -15,6 +17,7 @@ class MockClassTest extends \PHPUnit_Framework_TestCase */ public function should_mock_objects() { + /** @var ClassFixture $mock */ $mock = EasyMock::mock('EasyMock\Test\Fixture\ClassFixture'); $this->assertInstanceOf('PHPUnit_Framework_MockObject_MockObject', $mock); @@ -26,12 +29,24 @@ public function should_mock_objects() */ public function should_mock_interfaces() { + /** @var InterfaceFixture $mock */ $mock = EasyMock::mock('EasyMock\Test\Fixture\InterfaceFixture'); $this->assertInstanceOf('PHPUnit_Framework_MockObject_MockObject', $mock); $this->assertNull($mock->foo()); } + /** + * @test + */ + public function not_mocked_methods_should_return_null() + { + /** @var ClassFixture $mock */ + $mock = EasyMock::mock('EasyMock\Test\Fixture\ClassFixture'); + + $this->assertNull($mock->foo()); + } + /** * @test */ @@ -62,12 +77,15 @@ public function should_mock_existing_method_with_a_callback() /** * @test + * @expectedException \EasyMock\Test\Fixture\CustomException + * @expectedExceptionMessage My message */ - public function not_mocked_methods_should_return_null() + public function should_mock_existing_method_to_throw_exception() { /** @var ClassFixture $mock */ - $mock = EasyMock::mock('EasyMock\Test\Fixture\ClassFixture'); - - $this->assertSame(null, $mock->foo()); + $mock = EasyMock::mock('EasyMock\Test\Fixture\ClassFixture', array( + 'foo' => new CustomException('My message'), + )); + $mock->foo(); } }