25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7<br />

Testing Your <strong>Spring</strong> Application<br />

In this chapter, you are going to start using the <strong>Spring</strong> <strong>Framework</strong> Features. So far in previous chapters, you have been<br />

using the JUnit test framework, which is fine if you want to do simple testing. Previously, every time you needed to<br />

declare the application context’s implementation like the ClassPathXmlApplicationContext class. You did this by<br />

calling context = new ClassPathXmlApplicationContext("META-INF/spring/mydocuments-context.xml") to load<br />

your XML configuration file in order to use the <strong>Spring</strong> container.<br />

The <strong>Spring</strong> <strong>Framework</strong> Test library provides some features like unit testing by using JUnit or TestNG test,<br />

and integration testing. You can use mock objects based on environment, JNDI, Servlet, and Portlet APIs. For the<br />

integration testing, the <strong>Spring</strong> <strong>Framework</strong> provides a caching mechanism between test executions and transaction<br />

management, normally the latter regarding JDBC connections.<br />

From now on, your tests for each chapter will be using the integration testing features from the <strong>Spring</strong> Test<br />

library. The primary goals are to support the use of the ApplicationContext class so that when your tests start<br />

you always have access to the container’s beans. Also, this provides the use of dependency injection by using an<br />

annotation like @Autowired.<br />

Testing with Annotations<br />

You are going to start with annotations, which is one of the common uses of the <strong>Spring</strong> Test fixtures. So far you have<br />

been using the @Autowired annotation, but now you use the application context call. So, let’s modify your classes to<br />

use the testing annotations with no modification of the XML configuration (as shown in Listing 7-1).<br />

Listing 7-1. MyDocumentsTest.java<br />

package com.apress.isf.spring.test;<br />

import static org.junit.Assert.assertEquals;<br />

import static org.junit.Assert.assertNotNull;<br />

import static org.junit.Assert.assertTrue;<br />

import java.util.List;<br />

import org.junit.Test;<br />

import org.junit.runner.RunWith;<br />

import org.slf4j.Logger;<br />

import org.slf4j.LoggerFactory;<br />

import org.springframework.beans.factory.annotation.Autowired;<br />

import org.springframework.test.context.ContextConfiguration;<br />

import org.springframework.test.context.junit4.<strong>Spring</strong>JUnit4ClassRunner;<br />

75

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!