Java Reference
In-Depth Information
The interface in listing 13.4 is all we need to begin testing the consumers of our
DAO layer. We don't even need a completed implementation. Using JM ock, we
can easily mock the expected behavior for the getPerson() method. Consider the
service that makes use of the PersonDao interface (listing 13.5).
Listing 13.5
A service that makes use of PersonDao
public class PersonService {
private PersonDao personDao;
public PersonService(PersonDao personDao) {
this.personDao = personDao;
}
public Person getValidatedPerson(Integer personId) {
Person person = personDao.getPerson(personId);
validateAgainstPublicSystems(person);
validateAgainstPrivateSystems(person);
validateAgainstInternalSystems(person);
return person;
}
}
The target of our unit tests is not the DAO —it's the getValidatedPerson()
method logic, such as the various validations it performs. Each of the validations
may be a private method, and for argument's sake, let's just agree that we're only
testing the private interface here.
Testing this logic without a database will be easy, thanks to that PersonDao inter-
face that we saw earlier. All we need to do is mock the PersonDao , pass it to the con-
structor of our service, and call the getValidatedPerson() method. Listing 13.6
shows the unit test that does exactly that.
Listing 13.6
Using a mock instead of the real DAO to avoid hitting the database
public void testShouldRetrieveAValidatedPerson (){
final Integer PERSON_ID = new Integer(1);
Mock mock = new Mock(PersonDao.class);
mock.expects(once())
.method("getPerson")
Search WWH ::




Custom Search