On his HackerNoon site Sameer Nyaupane has posted part four of his series covering test-driven development in PHP. In this latest post he covers the use of mocking.
Hey there, welcome to part 4! Today we’ll learn how to mock. Mocking is a process where you create a fake instance of a real class, and test against it. This is so that, you do not have to worry about the real functionality of external dependencies inside a class. This makes unit testing a lot easier and reliable.
[...] Although PHPUnit does have mocking capabilities, it is not as full fledged as that of Mockery’s. We’ll be using Mockery for all our mocking needs.
He starts with some sample code, a simple
Math class that calculates the area of a square (but doesn't implement it fully). This includes the need for an instance of a
Calculate class that doesn't exist yet. He then works up a test for the
Math class, mocking the
Calculate class and calling the
getArea method to evaluate the result. He walks you through each line of the code, sharing what's happening during test execution.