Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mockito Beginner Question

 
yusuf Kaplan
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

following code:


returns 0 in Console. But I expect it to return 50.
ServiceImpl looks like:


and CustomerDAOImpl


Any suggestions?
 
Sresh Rangi
Ranch Hand
Posts: 54
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The service method is calling count, which is mocked to return 0 by default. In your test, you should mock the count method instead of the findAll method.
 
Junilu Lacar
Bartender
Pie
Posts: 7778
62
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To me, this flags a problem with the production code. Notice how the Service.count() method is simply a pass-through call to the DAO.count() method -- this construct is just useless overhead. I would rethink the purpose of having a count() method in the service class. Maybe it would be more useful to have something like this instead:


or something else that uses the size of the list to calculate a more abstract concept such as "requiresMultipleSalesRegions" or "belowMinimumRequiredLevel"
 
yusuf Kaplan
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sresh,

thanks for the answer.
ServiceImpl.count calls CustomerDAOImpl.count calls CustomerDAOImpl.findAll.
When my test runs into CustomerDAOImpl.findAll it should return the list with 50 entries.
I explicitly dont want to mock count(). I just want a method to be mocked which is deeper in the call hierarchy.

Sresh Rangi wrote:The service method is calling count, which is mocked to return 0 by default. In your test, you should mock the count method instead of the findAll method.
 
Sresh Rangi
Ranch Hand
Posts: 54
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With mocks, the call hierarchy ends when it reaches the mocked interface. To use the real implementation for one method and mock another, you can use partial mocking. Mockito can do this with spies:



or you could subclass CustomerDAOImpl and override findAll to return your list.

Spies are discouraged though, because you can usually redesign the program or the tests to not require partial mocking. This results in a clearer boundary between code under test, and dependent components.
 
yusuf Kaplan
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it.
Partial Mocking solved the problem.
Thanks for everybody
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic