Search⌘ K
AI Features

Unit Testing: Coding with Dependencies

Explore how to write unit tests for PHP code that relies on dependencies by using test doubles like stubs and mocks. Understand how dependency injection helps create deterministic, testable code and learn best practices for maintaining reliable tests and clean design.

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, ...