• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to test dynamic query method with TestNG and mockito

 
Brian Storenson
Ranch Hand
Posts: 44
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?




 
Junilu Lacar
Bartender
Pie
Posts: 6549
22
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Have a look at this example: http://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-four-jpa-criteria-queries/ ; you'll see an alternative nomenclature as well as a proper assignment of responsibility.
 
Brian Storenson
Ranch Hand
Posts: 44
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Junilu!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic