aspose file tools*
The moose likes Struts and the fly likes How to mock Hibernate Session? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "How to mock Hibernate Session?" Watch "How to mock Hibernate Session?" New topic
Author

How to mock Hibernate Session?

lydia edward
Greenhorn

Joined: Feb 02, 2011
Posts: 11
Hi

I am new to JUnit scripting. I need to write JUnit tests for code involving Hibernate sessions.

Can anyone please give me a sample working code which will mock Hibernate session objects and help me execute the tests without having to actually do any operations on the real DB.

For example how do I write the JUnit test for the following lines of code?



Any help appreciated.
Thanks!
Miguel Almeida
Greenhorn

Joined: Mar 12, 2010
Posts: 9
Hi Lydia,

The simple answer to your question is that you can use a library like EasyMock to help you. In simple terms, it works like so:



This is the general idea of working with mocks.

Now, as it might become apparent, your code needs quite a few expectations. This is because you are doing a lot of db stuff in the action itself that could be refactored somewhere else. For example, you could have a personService with a delete method, where you'd encapsulate your code in, say, a deleteUser(String username). In the the action you would therefore only have to mock one method (the deleteUser one), and you can simulate what you want to happen in your action for an array of situations (what if that method throws an exception? what if the user doesn't exist?): it's just a matter of mocking the expectations.

Another (simpler) way would be to encapsulate that code in a helper method in the action, like:



You can then test it in your class by overriding that method for testing purposes.


For more on this, I suggest the reading of Lasse Koskela's excellent Test Driven, which explores these strategies in the context of TDD.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to mock Hibernate Session?