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;

public class TestDao extends AbstractTestNGSpringContextTests{
    private Logger logger = Logger.getLogger(TestDao.class);

    public SessionFactory sessionFactory;
    private Session session;

    private NewsDao newsDao;

    private NewsCategoryDao newsCategoryDao;

     * Inisialisasi hibernate context sebelum test
    void init() {
        logger.debug("init session factory");
        session = sessionFactory.openSession();

     * cleanup hibernate context setelah test
    void destroy() {
        logger.debug("destroy session factory");

    public void testGetNews(){
        News news = newsDao.getById(1);"News ID : " + news.getId());"News Title : " + news.getNewsTitle());"News URL : " + news.getNewsUrl());"News Category : " + news.getNewsCategory().getCategoryName());"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.



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(
    at org.springframework.test.context.TestContextManager.prepareTestInstance(
    at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextPrepareTestInstance(
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(
    at java.lang.reflect.Method.invoke(
    at org.testng.internal.MethodInvocationHelper.invokeMethod(
    at org.testng.internal.Invoker.invokeConfigurationMethod(
    at org.testng.internal.Invoker.invokeConfigurations(
    at org.testng.internal.Invoker.invokeConfigurations(
    at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(
    at org.testng.TestRunner.privateRun(
    at org.testng.SuiteRunner.runTest(
    at org.testng.SuiteRunner.runSequentially(
    at org.testng.SuiteRunner.privateRun(
    at org.testng.SuiteRunnerWorker.runSuite(
    at org.testng.TestNG.runSuitesSequentially(
    at org.testng.TestNG.runSuitesLocally(
    at org.testng.remote.RemoteTestNG.initAndRun(
    at org.testng.remote.RemoteTestNG.main(
    Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [WEB-INF/applicationContext.xml]; nested exception is class path resource [WEB-INF/applicationContext.xml] cannot be opened because it does not exist
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(
    at org.springframework.test.context.TestContext.loadApplicationContext(
    at org.springframework.test.context.TestContext.getApplicationContext(
    … 28 more
    Caused by: class path resource [WEB-INF/applicationContext.xml] cannot be opened because it does not exist
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBea


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

    import org.testng.annotations.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;
    public void simpleTest() {

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

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s