Use the Spring Framework for testing . This allows unit test to use the Spring container configured for your application context. Once configured, you can use @Autowired on your data source to enter the data source required for testing jdbcTemplate.
Here is an example of one of my tests using Spring-Data.
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import org.tothought.entities.Post; import org.tothought.entities.PostPart; import org.tothought.entities.Tag; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @Transactional public class PostRepositoryTest { @Autowired TagRepository tagRepository; @Test public void findOneTest() { Post post = repository.findOne(1); assertNotNull(post); assertTrue(post.getTags().size()>1); } }
Note the annotation @ContextConfiguration . This annotation points to the context used to configure the Spring container, from which I then paste my repository. Since I did not specify a name for my context, Spring is looking for a configuration file in the same directory as my test class named PostRepositoryTest-context.xml. This setting is described in more detail in the above documentation.
To start using the project, include the following in the pom.xml file.
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.1.2.RELEASE</version> </dependency>
source share