Using TestNG on Spring Framework and Hibernate Test Case

Dear readers, at the time I wrote this article, I just have 2 months of being an employee at the IT Consultant Company in Jakarta, Indonesia. But that’s not what I want to share in this article. In this company, I was expected to follow the java development stack which is applied in this company. The Spring Framework and Hibernate are include.

I’ve been 6 years in Java programming language, but I admit, I never involve Hibernate framework as an ORM(Object Relational Mapping) method on my projects development stack. While Spring Framework, I’ve been using it since 2 years ago. This condition force me to do a little adaptation of this Hibernate Framework.

I often met some difficulties which is stress me so much, when the codes of the dao layer using a hibernate criteria. For a few developers who always using hibernate framework, it should be easier to use hibernate criteria, but for me, it really stress me so much.

To find a method on a dao layer work or not, sometimes it wouldn’t so effective to test it by deploying whole application just only to test one method. And I decide to use unit-test when testing dao layer methods, so I don’t need to deploy whole application.

Okay, below is the step to create a unit-test in order to test the methods on dao layer which created using Spring Framework and hibernate:

  1. Create a hibernate configuration file, Spring Context file, and all those supported files, and put them onto test/resources folder just like the picture below:
  2. Create a file called TestDao, and put it onto test/java folder. The codes of the files is below:
package com.mojo.maven.test;

import com.mojo.maven.dao.NewsCategoryDao;
import com.mojo.maven.dao.NewsDao;
import com.mojo.maven.model.News;
import com.mojo.maven.model.NewsCategory;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.context.ManagedSessionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

@ContextConfiguration(locations={"classpath*:maven1ApplicationContext-test.xml"})
public class TestDao extends AbstractTestNGSpringContextTests{
    private Logger logger = Logger.getLogger(TestDao.class);

    @Autowired
    public SessionFactory sessionFactory;
    private Session session;

    @Autowired
    private NewsDao newsDao;

    @Autowired
    private NewsCategoryDao newsCategoryDao;

    /**
     * Inisialisasi hibernate context sebelum test
     */
    @BeforeMethod
    void init() {
        logger.debug("init session factory");
        session = sessionFactory.openSession();
        ManagedSessionContext.bind(session);
    }

    /**
     * cleanup hibernate context setelah test
     */
    @AfterMethod
    void destroy() {
        logger.debug("destroy session factory");
        session.close();
        ManagedSessionContext.unbind(sessionFactory);
    }

    @Test
    public void testGetNews(){
        News news = newsDao.getById(1);
        logger.info("News ID : " + news.getId());
        logger.info("News Title : " + news.getNewsTitle());
        logger.info("News URL : " + news.getNewsUrl());
        logger.info("News Category : " + news.getNewsCategory().getCategoryName());
        logger.info("News Category Description : " + news.getNewsCategory().getCategoryDescription());
    }
}

What we have to pay attention on the class are, the class have an annotation @ContextConfiguration and extends AbstractTestNGSpringContextTests class which is provide as a base class to use it as a test class for TestNG Framework. Also on the annotation @ContextConfiguration  defined the location of the Spring Context, so the compiler can find a Spring Context file when the execution is triggered.

The next thing which have to note are 2 methods which is defined on the class, those are void init() method and void destroy() method. void init() method, given an annotation @BeforeMethod which have a function as an hibernate context initializations before all other the test method executed. While void destroy() method given an annotation @AfterMethod which have a function to close a hibernate session after all test method executed.

Well, that’s all that I can share for this time. If you feel the codes need more improvement, so go head, to make it perfect.

I’ll hope it usefull.

Josescalia

———————————————-

3 thoughts on “Using TestNG on Spring Framework and Hibernate Test Case

  1. Hi,
    very nice article, I followed this but I cannot able to configure the class path for applicationcontext.xml
    It is throwing
    FAILED CONFIGURATION: @BeforeClass springTestContextPrepareTestInstance
    java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:201)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:255)
    at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextPrepareTestInstance(AbstractTestNGSpringContextTests.java:117)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:551)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
    at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:175)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:107)
    at org.testng.TestRunner.privateRun(TestRunner.java:768)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:87)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1185)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1110)
    at org.testng.TestNG.run(TestNG.java:1022)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:109)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:202)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:173)
    Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [WEB-INF/applicationContext.xml] cannot be opened because it does not exist
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:212)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:81)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:42)
    at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:173)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:197)
    … 28 more
    Caused by: java.io.FileNotFoundException: class path resource [WEB-INF/applicationContext.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBea

    package com.company.abc.test.TestNG;

    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
    import org.testng.AssertJUnit;

    import org.testng.annotations.Test;

    import com.company.abc.test.TestNG.dao.UserProfileDAO;

    @Test
    @ContextConfiguration(locations = { “classpath:WEB-INF/applicationContext.xml” })
    public class UserProfileDAOTest extends AbstractTransactionalTestNGSpringContextTests {

    private static final String USRID = “S003339”;
    private static final String PSWD = “String1”;
    UserProfileDAO userProfileDAO;
    //@Rollback(true)
    public void simpleTest() {

    // AssertJUnit.assertNotNull(“2”, “User 1 could not be retrieved.”);
    int rowsAffected =userProfileDAO.userExist(USRID);
    AssertJUnit.assertEquals(1,rowsAffected);
    }
    }

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s