2014年12月26日星期五

Robert Basic: Mocking hard dependencies with Mockery


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.


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

没有评论:

发表评论