In this new post to his blog Chris Hartjes gets into some details about some complex mocking he recently had to do in a project for work. He includes code snippets to illustrate.
With such an extensive array of tests [at work], I have received an education in what it really means to write unit tests for live, production-ready code that really takes unit testing seriously. [...] If you are really writing your unit tests the way you should, each test is focusing on testing one bit of functionality in isolation, which means that you will be heavily relying on mock objects to make things work. I've come up with an example scenario that I hope goes a long way to explaining how to effectively use mock objects.
In his example, he shows how to mock out two objects, "Foo" and "Bar" that are passed into a method in his "Alpha" class. He looks at the code for the "Foo" class and creates a mock object based on its contents - two methods: "getId" and "getDetails". He does the same with the "Bar" class, mocking the "getStartDate" and "getEndDate" methods and showing how to pass those into the "munge" method on the "Alpha" class, complete with return values to match the tests.
For more information on PHPUnit's mock object support, see this page in its manual. You might also explore another popular option, Mockery.
没有评论:
发表评论