Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Robert Basic:
Mocking hard dependencies with Mockery
Dec 26, 2014 @ 17:14:51

Robert Basic has a post today showing how you can mock hard dependencies with Mockery, a mocking library for use in unit testing. In this case, "hard" refers to work around the use of "new" creating objects in hard to test places.

One problem with unit testing legacy applications is that the code has new statements all over the place, instantiating new objects in a way that doesn't really makes it easier to test the code. Of course, the easy answer to this is "Just refactor your application!", but that's almost always easier said than done. If refactoring is an option, do it. If not, one option is to use Mockery to mock the hard dependencies.

He makes use of instance mocks to show the overloading of the service without the need for a refactor. This overrides it on a more global scale, so it could have an effect on other tests. He shows how autoloading and PHPUnit's own process isolation handling can fix tis problem (though it takes more time to run the tests this way). He includes sample code of the whole process so you can easily follow along too.

tagged: mockery dependency hard new instance phpunit unittest

Link: http://robertbasic.com/blog/mocking-hard-dependencies-with-mockery


Trending Topics: