Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Unit testing with JUnit 4 using Spring's application context


JUnit tests are run outside Spring; Spring is not initialized before the tests are run. To be able to use the beans defined in the configuration files and dependency injection, some bootstrapping code needs to be added to the test class.

How to do it…

Follow these steps to test a method using the Spring's application context with JUnit 4:

  1. Add the spring-test Maven dependency in pom.xml:

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.1.1.RELEASE</version>
      <scope>test</scope>
    </dependency>
  2. Add these annotations to the test class:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = {AppConfig.class})
    @WebAppConfiguration
    public class TestControllerTest {
    …
  3. Use Spring beans as usual, for example, as @Autowired fields:

    @Autowired
    private UserDAO userDAO;
    
    @Test
    public void testListUsers() {
      List<User...