As we stated previously, we want to isolate the code being tested from the rest of the code base.
A database lookup, though, will require database libraries, data model code, a running database, proper setup of the data in the database, etc.
The first step should be to isolate the database code from your code. You can do this by providing some interface that matches your data model and provides convenience methods for lookups.
All SQL, driver configuration, etc. will be hidden behind this interface, so your code that requires a lookup may simply call something like:
final User u = db.lookupUserById(10);
The db object can then be passed into our object or method and, since we have “programmed to an interface,” we can replace this object with any instance of the same interface.
To properly isolate the our code from the database lookup when testing, we could provide a mock for the database lookup object.
In other words, we can create a class that matches the necessary interface, but does not actually interact with a database!
In our unit test, we will create a mock that is configured to return a specific instance of the User class when the lookup method is called with the value 10, and then we can write our test with the assumption that the lookup succeeds!
If we mock all dependencies in a method or class using this, approach, then we know that any errors are caused solely by the method or class logic itself, and not by dependencies.
This also makes it easier to write tests, because a lot of code my be required to create real instances that you could use, but mocks are usually rather trivial to create.