The first thing we need to understand is that if we create objects
using new
inside the controller, we will not be able to
mock them. This means that we need to inject all the
dependencies—for example, using a dependency injector. We will do
this for all of the dependencies but one: the models. In this
section, we will test the borrow
method
of the BookController
class, so we will
show the changes that this method needs. Of course, if you want to
test the rest of the code, you should apply these same changes to
the rest of the controllers.
The first thing to do is to add the
BookModel
instance to the dependency
injector in our index.php
file. As this
class also has a dependency, PDO
, use
the same dependency injector to get an instance of it, as
follows:
$di->set('BookModel', new BookModel($di->get('PDO')));
Now, in the borrow
method of the BookController
class, we
will change the new instantiation of the model to the
following:
public function borrow(int $bookId): string {
$bookModel = $this->di->get('BookModel');
try {
//...