Skip to content

Instantly share code, notes, and snippets.

@yclian
Created September 12, 2011 08:00
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yclian/1210790 to your computer and use it in GitHub Desktop.
Save yclian/1210790 to your computer and use it in GitHub Desktop.
Mocking a Hibernate session / testing Criteria
package yourpackage;
import static org.mockito.Mockito.*;
import java.util.HashMap;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.function.SQLFunctionRegistry;
import org.hibernate.engine.SessionFactoryImplementor;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public abstract class HibernateTest {
SessionFactory sf;
SessionFactoryImplementor sfi;
@Mock
Session s;
@Mock
HibernateTemplate t;
@Before
public void setUp() throws Exception {
sf = mock(SessionFactory.class, withSettings().extraInterfaces(SessionFactoryImplementor.class));
sfi = (SessionFactoryImplementor) sf;
when(sf.openSession()).thenReturn(s);
when(sfi.getSqlFunctionRegistry()).thenReturn(new SQLFunctionRegistry(new MySQL5Dialect(), new HashMap<Object, Object>()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment