Unit Testing: Coding with Dependencies

Learn how to use mocks and stubs to test classes with dependencies.

We can unit test things that depend on something else. To test them in isolation, we must replace all the dependencies with dummy implementations called test doubles. Fortunately, with mocking libraries, making such dummy implementations is easy.

PHPUnit has built-in mocking functionality, but phpspec/prophecy provides a friendlier API.

Stubs for dependencies that provide data

We use stubs for dependencies that only provide data. Stubs return dummy data so our function can work.

For example, let’s create a function that creaties a time-related greeting. It will return “Good morning!” in the morning, “Good afternoon!” during the day, and “Good evening!” in the evening. It’s hard to test such a function because it returns different outputs based on when we run it. But, we can make it deterministic by moving the code that retrieves the current time to dependencies and using the dependency injection to provide it.

Get hands-on with 1200+ tech skills courses.