Reputation: 72
Is it possible to make Mock object for Hiberate's native classes(I use easymock)? For example for Query? If yes, how should I do it?
Here is part of test code:
@Mock
private SessionFactory sessionFactory;
@Mock
protected Session session;
@Mock
protected Query query;
@Before
public void setUp() {
***
pageService.setQuery(query);
pageService.setSession(session);
}
String hqlUniquenessCheck - it is a select request
expect(sessionFactory.getCurrentSession().createQuery(hqlUniquenessCheck)).andReturn(query);
But on line expect*** I got java.lang.NullPointerException. What can be wrong?
Many thanks in advance.
Upvotes: 0
Views: 2054
Reputation: 7739
Hibernate classes are not native classes. You can mock a hibernate class, just like any other class in your application.
Native classes are classes which have the native
java keyword. This means that they include bytecode which is not java code. All of hibernate's code is java code, and is available from hibernate.org. (If you are using maven, you can use -DdownloadSources=true
, or set the equivalent setting in your IDE. This will show you the source code for your libraries.) Note that you do not need to have the source in order to mock the objects.
Query
is an interface, so you can mock it just like any other interface, using the framework. Check out the framework's documentation:
http://www.betgenius.com/mockobjects.pdf
Edit:
It's worth noting that hibernate does generate proxies for persistent objects at runtime. You will see something like $$EnhancerByCGLIB
in the classname for these proxies. These proxies do have native code, and you should not try to mock them. Instead of trying to mock a real persistent object from the session, mock the Session
, which is itself an interface, mock the Query
, and create your own mock object from the query results.
Upvotes: 3