Unit Testing EJB3 + Hibernate Using OpenEJB + TestNG + jMockIt - Part II

In my previous blog I explained how to create a stateless bean, how to configure Hibernate model class, Hibernate hbm file and a DAO class for accessing data.

In this section, I will explain how to write test class for our stateless bean UserInfoBean.java.


1. Mock HibernateUtil.java
You can use existing HibernateUtil class or mock the class to include custom properties which is needed only for unit testing. A sample given below:
public class MockedHibernateUtil {
   private static SessionFactory sessionFactory;
   public static SessionFactory getSessionFactory() {
      if (null == sessionFactory) {
         sessionFactory = new Configuration().configure(
     new File("test-hibernate.cfg.xml")).buildSessionFactory();
      return sessionFactory;
2. Mocked Service Locator
public class MockedServiceLocator {
   public static Object getEjb(String jndiName) throws Exception{
 InitialContext initialContext = null;
 Properties properties = new Properties();
 initialContext = new InitialContext(properties);
 return initialContext.lookup(jndiName);
3. Mocker class
public class Mocker {
   public static void mockHibernateUtil() {
      Mockit.redefineMethods(HibernateUtil.class, MockedHibernateUtil.class);
   public static void mockServiceLocator() {
      Mockit.redefineMethods(ServiceLocator.class, MockedServiceLocator.class);
4. Test data provider class
public class UserInfoBeanTestDataProvider {
   @DataProvider(name = "testUserInfoDataProvider")
   public static Object[][] testUserInfoDataProvider() {
      return new Object[][] { { "john" }, { "tracy" }, { "leo" } };
5. Test class
public class HelloBeanTest {
   private static InitialContext initialContext;
   public void setUp() {

   @Test(groups = { "usergroup" }, dataProviderClass = 
   UserInfoBeanTestDataProvider.class, dataProvider = "testUserInfoDataProvider")
   public void testGetUserName(String arg) throws NamingException {
      Object obj = ServiceLocator.getEjb("jndi.UserInfo");
      assert (null != obj) : "obj is null";
      UserInfo userInfo = (UserInfo) obj;

   protected void tearDown() {
      // clean up

Go back to Part I


  1. Hi!

    I'm trying to do the same, but using jUnit 4 instead of TestNG.

    Why didn't you use the jMockit Hibernate3Emul to avoid mocking DAOs and the MOR engine? Any special issue?



Post a comment

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to our feed and get articles like this delivered automatically to your feed reader? Like our Facebook Page.

Popular posts from this blog

Induction Cooker Showing an Error Code? Induction Cooker Error Codes Explained

How to Child Lock Channels on Airtel Digital TV

LICHFL - Generating Home Loan Statements Online