This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I am new to unit testing, and I am trying to test the handleCriteria(). I wanted to verify that root.get(Person_.firstName) on line 26 occurred. But, I am getting a null pointer exception. I am having a hard time figuring out how to mock things, and use when(). I have read some of the mockito docs, and other tutorials. According to stack,
"A unit test should test a single codepath through a single method. When the execution of a method passes outside of that method, into another object, and back again, you have a dependency.
When you test that code path with the actual dependency, you are not unit testing; you are integration testing. While that's good and necessary, it isn't unit testing."
How can I test handleCriteria, and get rid of this null pointer exception?
When something is difficult to test, sometimes it's an indication that either your test or class under test has a design flaw. Looking at the code you provided, I would say that it's primarily the design of the class under test that has some problems that you should fix.
The biggest smell is that of inappropriate assignment of responsibility. A Data Access Object is responsible for mapping the structure of data in the persistence mechanism (in this case, an RDBMS) to/from the object structure. The code you are trying to test supports this responsibility but doesn't necessarily fulfill it. My first inclination would be to refactor this code, extracting the criteria building functionality out to another class. Hints as to what class it should be extracted out to can be found in the method signature, which also has some code smells.
One of those code smells is that the method name "handleCriteria" doesn't really say much about the intent of the method and doesn't make a lot of sense semantically in the context of the declared return type and the parameters passed in. A name like "createQuery" or "createQueryFor" would make more sense to me, with only one parameter necessary: the criteria map.