reset password

Testing

There are two popular Java testing frameworks: JUnit and TestNG. There was a time when TestNG was considered technically superior, but these days these two are pretty much the same. In this section we will describe how to use TestNG to test database access.

1. Add the following dependencies:

  • org.testng:testng
  • org.springframework:spring-test

and set the scope of both dependencies to test.

2. Copy src/main/webapp/WEB-INF/applicationContext.xml to src/test/resources. This bean configuration file will be used by the testing code to initialize the Spring framework and create beans for data sources, entity manager, and so on.

3. Create a test class as follows and place it under src/test/java/springmvc/model/dao:

package springmvc.model.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.testng.annotations.Test;

@Test(groups = "UserDaoTest")
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class UserDaoTest extends AbstractTransactionalTestNGSpringContextTests {

    @Autowired
    UserDao userDao;

    @Test
    public void getUser()
    {
        assert userDao.getUser( 1 ).getUsername().equalsIgnoreCase( "admin" );
    }

    @Test
    public void getUsers()
    {
        assert userDao.getUsers().size() == 2;
    }

}

In Eclipse, right click the class and select Run As -> TestNG Test. If you have created the database using springmvc-create.sql as described in the previous step, both tests should pass.

This page has been viewed 5660 times.