As Juergen Hoeller mentioned in his post announcing the release of Spring Framework 3.2 RC1, the Spring Team has introduced some exciting new features in terms of testing support. Most importantly, we've added first-class support for testing web applications. [1]
Please note: this is a cross post from my Swiftmind company blog.
In this post we'll first take a look at some of the general new testing features in the Spring Framework, and then we'll go into detail regarding support for testing with a WebApplicationContext
as well as request and session scoped beans. We'll close with a look at support for ApplicationContextInitializers
and a brief discussion of the road map for testing with application context hierarchies.
Rossen Stoyanchev will later follow up with a detailed post on the new Spring MVC Test framework that provides first-class support for testing Spring MVC applications. So be sure to stay tuned for that as well, since it builds on the basic web testing support discussed later in this post.
General New Features and Updates
Build and Dependencies
The spring-test
module now builds against and supports JUnit 4.10 and TestNG 6.5.2, and spring-test
now depends on the junit:junit-dep
Maven artifact instead of junit:junit
which means that you have full control over your dependencies on Hamcrest libraries (e.g., hamcrest-core
, hamcrest-all
, etc.).
Generic Factory Methods
Generic factory methods are methods that implement the Factory Method Design Pattern using Java Generics. Here are some example signatures of generic factory methods:
public static <T> T mock(Class<T> clazz) { ... }
public static <T> T proxy(T obj) { ... }
The use of generic factory methods in Spring configuration is by no means specific to testing, but generic factory methods such as EasyMock.createMock(MyService.class)
or Mockito.mock(MyService.class)
are often used to create dynamic mocks for Spring beans in a test application context. For example, prior to Spring Framework 3.2 the following configuration could fail to autowire the OrderRepository
into the OrderService
. The reason is that, depending on the order in which beans are initialized in the application context, Spring would potentially infer the type of the orderRepository
bean to be java.lang.Object
instead of com.example.repository.OrderRepository
.
<beans>
<!-- OrderService is autowired with OrderRepository -->
<context:component-scan base-package="com.example.service"/>
<bean id="orderRepository" class="org.easymock.EasyMock…