0

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.

Ana
  • 72
  • 4
  • 2
    Have you tried mocking an interface before? Not much is different. **Try before you ask!** IMHO mocking JPA is a complete waste if time. – Adam Gent Apr 07 '13 at 15:24
  • I have been trying to do it before I asked you, but I failed, I heard that there can be some troubles with mocking native components and there can be some peculiarities. Don't be fast telling that I didn' try. – Ana Apr 07 '13 at 15:35
  • 1. I don't know what a native component is. Do you mean concrete class (ie not an interface). 2. What code did you try and what failed (put it in your question). – Adam Gent Apr 07 '13 at 16:33

1 Answers1

3

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.

RMorrisey
  • 7,637
  • 9
  • 53
  • 71