Below you will find pages that utilize the taxonomy term “Mocking”
Mocking the network
In this series, we’ve discussed several topics already. We talked about persistence and time, the filesystem and randomness. The conclusion for all these areas: whenever you want to “mock” these things, you may look for a solution at the level of programming tools used (use database or filesystem abstraction library, replace built-in PHP functions, etc.). But the better solution is always: add your own abstraction. Start by introducing your own interface (including custom return types), which describes exactly what you need. Then mock this interface freely in your application. But also provide an implementation for it, which uses “the real thing”, and write an integration test for just this class.
Mocking at architectural boundaries: the filesystem and randomness
In a previous article, we discussed “persistence” and “time” as boundary concepts that need mocking by means of dependency inversion: define your own interface, then provide an implementation for it. There were three other topics left to cover: the filesystem, the network and randomness.
Mocking the filesystem
We already covered “persistence”, but only in the sense that we sometimes need a way to make in-memory objects persistent. After a restart of the application we should be able to bring back those objects and continue to use them as if nothing happened.
Mocking at architectural boundaries: persistence and time
More and more I’ve come to realize that I’ve been mocking less and less.
The thing is, creating test doubles is a very dangerous activity. For example, what I often see is something like this:
$entityManager = $this->createMock(EntityManager::class);
$entityManager->expects($this->once())
->method('persist')
->with($object);
$entityManager->expects($this->once())
->method('flush')
->with($object);
Or, what appears to be better, since we’d be mocking an interface instead of a concrete class:
$entityManager = $this->createMock(ObjectManagerInterface::class);
// ...
To be very honest, there isn’t a big different between these two examples. If this code is in, for example, a unit test for a repository class, we’re not testing many of the aspects of the code that should have been tested instead.