The Spring team considers developer testing to be an absolutely integral part of enterprise software development. A thorough treatment of testing in the enterprise is beyond the scope of this chapter; rather, the focus here is on the value-add that the adoption of the IoC principle can bring to unit testing and on the benefits that the Spring Framework provides in integration testing.
One of the main benefits of Dependency Injection is that your code should really depend far less on the container than in traditional J2EE development. The POJOs that comprise your application should be testable in JUnit or TestNG tests, with objects simply instantiated using the new operator, without Spring or any other container. You can use mock objects (in conjunction with many other valuable testing techniques) to test your code in isolation. If you follow the architecture recommendations around Spring you will find that the resulting clean layering and componentization of your codebase will naturally facilitate easier unit testing. For example, you will be able to test service layer objects by stubbing or mocking DAO or Repository interfaces, without any need to access persistent data while running unit tests.
True unit tests typically will run extremely quickly, as there is no runtime infrastructure to set up, whether application server, database, ORM tool, or whatever. Thus emphasizing true unit tests as part of your development methodology will boost your productivity. The upshot of this is that you often do not need this section of the testing chapter to help you write effective unit tests for your IoC-based applications. For certain unit testing scenarios, however, the Spring Framework provides the following mock objects and testing support classes.
The org.springframework.mock.jndi package contains an implementation of the JNDI SPI, which is useful for setting up a simple JNDI environment for test suites or stand-alone applications. If, for example, JDBC DataSources get bound to the same JNDI names in test code as within a J2EE container, both application code and configuration can be reused in testing scenarios without modification.
The org.springframework.mock.web package contains a comprehensive set of Servlet API mock objects, targeted at usage with Spring's Web MVC framework, which are useful for testing web contexts and controllers. These mock objects are generally more convenient to use than dynamic mock objects (e.g., EasyMock) or existing Servlet API mock objects (e.g., MockObjects).
The org.springframework.test.util package contains ReflectionTestUtils, which is a collection of reflection-based utility methods for use in unit and integration testing scenarios in which the developer would benefit from being able to set a non-public field or invoke a non-public setter method when testing application code involving, for example:
ORM frameworks such as JPA and Hibernate which condone the usage of private or protected field access as opposed to public setter methods for properties in a domain entity
Spring's support for annotations such as @Autowired and @Resource which provides dependency injection for private or protected fields, setter methods, and configuration methods
The org.springframework.test.web package contains AbstractModelAndViewTests, which serves as a convenient base class for JUnit 3.8 based unit tests dealing with Spring MVC ModelAndView objects. When developing against Java 1.4 and higher (e.g., in combination with JUnit 4+, TestNG, etc.), you have the option of using the ModelAndViewAssert class (in the same package) to test your ModelAndView related functionality.
Tip: depending on your testing environment, either extend AbstractModelAndViewTests or use ModelAndViewAssert directly and then use MockHttpServletRequest, MockHttpSession, etc. from the org.springframework.mock.web package to test your Spring MVC Controllers.
It is important to be able to perform some integration testing without requiring deployment to your application server or connecting to other enterprise infrastructure. This will enable you to test things such as:
The correct wiring of your Spring IoC container contexts.
Data access using JDBC or an ORM tool. This would include such things as the correctness of SQL statements, Hibernate queries, JPA entity mappings, etc.
The Spring Framework provides first class support for integration testing in the form of the classes that are packaged in the spring-test.jar library. In this library, you will find the org.springframework.test package which contains valuable classes for integration testing using a Spring container, while at the same time not being reliant on an application server or other deployment environment. Such tests will be slower to run than unit tests but much faster to run than the equivalent Cactus tests or remote tests relying on deployment to an application server.
Prior to the 2.5 release of the framework, Spring provided integration testing support specific to JUnit 3.8. As of the 2.5 release, Spring offers support for unit and integration testing in the form of the Spring TestContext Framework, which is agnostic of the actual testing framework in use, thus allowing instrumentation of tests in various environments including JUnit 3.8, JUnit 4.4, TestNG, etc. Note that the Spring TestContext Framework requires Java 5+.
The Spring team recommends using the Spring TestContext Framework for all new unit testing or integration testing involving ApplicationContexts or requiring transactional test fixtures; however, if you are developing in a pre-Java 5 environment, you will need to continue to use the JUnit 3.8 legacy support. In addition, explicit integration testing support for JPA which relies on shadow class loading for JPA class instrumentation is currently only available with the JUnit 3.8 legacy support. If you are testing against a JPA provider which does not require class instrumentation, however, it is recommended that you use the TestContext framework.
The Spring integration testing support frameworks share several common goals, including:
Spring IoC container caching between test execution.
Dependency Injection of test fixture instances (this is nice).
Transaction management appropriate to integration testing (this is even nicer).
Spring-specific support classes that are really useful when writing integration tests.
The following sections outline each of these goals and provide direct links to information specific to the particular support frameworks.
Spring integration testing support frameworks provide consistent loading of Spring ApplicationContexts and caching of those contexts. Support for the caching of loaded contexts is important, because if you are working on a large project, startup time may become an issue - not because of the overhead of Spring itself, but because the objects instantiated by the Spring container will themselves take time to instantiate. For example, a project with 50-100 Hibernate mapping files might take 10-20 seconds to load the mapping files, and incurring that cost before running every single test in every single test fixture will lead to slower overall test runs that could reduce productivity.
Test classes will generally provide an array containing the resource locations of XML configuration metadata - typically on the classpath - used to configure the application. This will be the same, or nearly the same, as the list of configuration locations specified in web.xml or other deployment configuration.
By default, once loaded, the configured ApplicationContext will be reused for each test. Thus the setup cost will be incurred only once (per test fixture), and subsequent test execution will be much faster. In the unlikely case that a test may 'dirty' the application context, requiring reloading - for example, by changing a bean definition or the state of an application object - Spring's testing support provides mechanisms to cause the test fixture to reload the configurations and rebuild the application context before executing the next test.
Context management and caching with:
When Spring integration testing support frameworks load your application context, they can optionally configure instances of your test classes via Dependency Injection. This provides a convenient mechanism for setting up test fixtures using pre-configured beans from your application context. A strong benefit here is that you can reuse application contexts across various testing scenarios (e.g., for configuring Spring-managed object graphs, transactional proxies, DataSources, etc.), thus avoiding the need to duplicate complex test fixture set up for individual test cases.
As an example, consider the scenario where we have a class, HibernateTitleDao, that performs data access logic for say, the Title domain object. We want to write integration tests that test all of the following areas:
The Spring configuration: basically, is everything related to the configuration of the HibernateTitleDao bean correct and present?
The Hibernate mapping file configuration: is everything mapped correctly and are the correct lazy-loading settings in place?
The logic of the HibernateTitleDao: does the configured instance of this class perform as anticipated?
Dependency Injection of test fixtures with:
One common issue in tests that access a real database is their affect on the state of the persistence store. Even when you're using a development database, changes to the state may affect future tests. Also, many operations - such as inserting to or modifying persistent data - cannot be performed (or verified) outside a transaction.
The Spring integration testing support frameworks meet this need. By default, they create and roll back a transaction for each test. You simply write code that can assume the existence of a transaction. If you call transactionally proxied objects in your tests, they will behave correctly, according to their transactional semantics. In addition, if test methods delete the contents of selected tables while running within a transaction, the transaction will roll back by default, and the database will return to its state prior to execution of the test. Transactional support is provided to your test class via a PlatformTransactionManager bean defined in the test's application context.
If you want a transaction to commit - unusual, but occasionally useful when you want a particular test to populate or modify the database - the Spring integration testing support frameworks can be instructed to cause the transaction to commit instead of roll back either by calling an inherited hook-method or by declaring a specific annotation.
Transaction management with:
The Spring integration testing support frameworks provide several abstract support classes that can simplify writing integration tests. These base test classes provide well defined hooks into the testing framework as well as convenient instance variables and methods, allowing access to such things as:
The ApplicationContext: useful for performing explicit bean lookups or testing the state of the context as a whole.
A JdbcTemplate or SimpleJdbcTemplate: useful for querying to confirm state. For example, you might query before and after testing application code that creates an object and persists it using an ORM tool, to verify that the data appears in the database. (Spring will ensure that the query runs in the scope of the same transaction.) You will need to tell your ORM tool to 'flush' its changes for this to work correctly, for example using the flush() method on Hibernate's Session interface.
Often you will provide an application-wide superclass for integration tests that provides further useful instance variables used in many tests.
Support classes for:
The org.springframework.test.jdbc package contains SimpleJdbcTestUtils, which is a Java-5-based collection of JDBC related utility functions intended to simplify standard database testing scenarios. Note that AbstractTransactionalJUnit38SpringContextTests, AbstractTransactionalJUnit4SpringContextTests, and AbstractTransactionalTestNGSpringContextTests provide convenience methods which delegate to SimpleJdbcTestUtils internally.
The Spring Framework provides a common set of Spring-specific annotations in the org.springframework.test.annotation package that you can use in your testing if you are developing against Java 5 or greater.
@IfProfileValue
Indicates that the annotated test is enabled for a specific testing environment. If the configured ProfileValueSource returns a matching value for the provided name, the test will be enabled. This annotation can be applied to an entire class or individual methods.
@IfProfileValue(name="java.vendor", value="Sun Microsystems Inc.")
public void testProcessWhichRunsOnlyOnSunJvm() {
// some logic that should run only on Java VMs from Sun Microsystems
}
Alternatively @IfProfileValue may be configured with a list of values (with OR semantics) to achieve TestNG-like support for test groups in a JUnit environment. Consider the following example:
@IfProfileValue(name="test-groups", values={"unit-tests", "integration-tests"})
public void testProcessWhichRunsForUnitOrIntegrationTestGroups() {
// some logic that should run only for unit and integration test groups
}
@ProfileValueSourceConfiguration
Class-level annotation which is used to specify what type of ProfileValueSource to use when retrieving profile values configured via the @IfProfileValue annotation. If @ProfileValueSourceConfiguration is not declared for a test, SystemProfileValueSource will be used by default.
@ProfileValueSourceConfiguration(CustomProfileValueSource.class)
public class CustomProfileValueSourceTests {
// class body...
}
@DirtiesContext
The presence of this annotation on a test method indicates that the underlying Spring container is 'dirtied' during the execution of of the test method, and thus must be rebuilt after the test method finishes execution (regardless of whether the test passed or not).
@DirtiesContext
public void testProcessWhichDirtiesAppCtx() {
// some logic that results in the Spring container being dirtied
}
@ExpectedException
Indicates that the annotated test method is expected to throw an exception during execution. The type of the expected exception is provided in the annotation, and if an instance of the exception is thrown during the test method execution then the test passes. Likewise if an instance of the exception is not thrown during the test method execution then the test fails.
@ExpectedException(SomeBusinessException.class)
public void testProcessRainyDayScenario() {
// some logic that should result in an Exception being thrown
}
@Timed
Indicates that the annotated test method has to finish execution in a specified time period (in milliseconds). If the text execution time takes longer than the specified time period, the test fails.
Note that the time period includes execution of the test method itself, any repetitions of the test (see @Repeat), as well as any set up or tear down of the test fixture.
@Timed(millis=1000)
public void testProcessWithOneSecondTimeout() {
// some logic that should not take longer than 1 second to execute
}
@Repeat
Indicates that the annotated test method must be executed repeatedly. The number of times that the test method is to be executed is specified in the annotation.
Note that the scope of execution to be repeated includes execution of the test method itself as well as any set up or tear down of the test fixture.
@Repeat(10)
public void testProcessRepeatedly() {
// ...
}
@Rollback
Indicates whether or not the transaction for the annotated test method should be rolled back after the test method has completed. If true, the transaction will be rolled back; otherwise, the transaction will be committed. Use @Rollback to override the default rollback flag configured at the class level.
@Rollback(false)
public void testProcessWithoutRollback() {
// ...
}
@NotTransactional
The presence of this annotation indicates that the annotated test method must not execute in a transactional context.
@NotTransactional
public void testProcessWithoutTransaction() {
// ...
}
Annotation support for:
JUnit 3.8 legacy support: all common annotations listed above are supported but must be used in conjunction with AbstractAnnotationAwareTransactionalTests in order for the presence of these annotations to have any effect.
The TestContext Framework: supports all of the common annotations listed above while providing additional TestContext-specific and transactional annotations (e.g., @ContextConfiguration, @BeforeTransaction, etc.). Note, however, that some of the common annotations are only supported when used in conjunction with JUnit (e.g., with the SpringJUnit4ClassRunner or the JUnit 3.8 and JUnit 4.4 base test classes). Refer to the documentation in the TestContext Framework section for further details.
Spring's JUnit 3.8 legacy support is comprised of the classes found in the org.springframework.test package. This package provides valuable JUnit TestCase superclasses which can be extended for out-of-container integration tests involving Spring ApplicationContexts or requiring transactional support at the test method level.
AbstractSingleSpringContextTests provides context management and caching support for JUnit 3.8 based test cases and exposes a protected method that subclasses can override to provide the location of context definition files:
protected String[] getConfigLocations()
Implementations of this method must provide an array containing the resource locations of XML configuration metadata - typically on the classpath - used to configure the application. This will be the same, or nearly the same, as the list of configuration locations specified in web.xml or other deployment configuration. As an alternative you may choose to override one of the following. See the respective JavaDoc for further details.
protected String[] getConfigPaths()
protected String getConfigPath()
By default, once loaded, the configuration file set will be reused for each test case. Thus the setup cost will be incurred only once (per test fixture), and subsequent test execution will be much faster. In the unlikely case that a test may 'dirty' the application context, requiring reloading - for example, by changing a bean definition or the state of an application object - you can call the setDirty() method on AbstractSingleSpringContextTests to cause the test fixture to reload the configurations and rebuild the application context before executing the next test case. As an alternative, if you are developing against Java 5 or greater and extending AbstractAnnotationAwareTransactionalTests, you may annotate your test method with @DirtiesContext to achieve the same effect.
When AbstractDependencyInjectionSpringContextTests (and subclasses) load your application context, they can optionally configure instances of your test classes by Setter Injection. All you need to do is to define instance variables and the corresponding setter methods. AbstractDependencyInjectionSpringContextTests will automatically locate the corresponding object in the set of configuration files specified in the getConfigLocations() method.
Consider the scenario where we have a class, HibernateTitleDao (as outlined in the Common goals section). Let's look at a JUnit 3.8 based implementation of the test class itself (we will look at the configuration immediately afterwards).
public final class HibernateTitleDaoTests extends AbstractDependencyInjectionSpringContextTests { // this instance will be (automatically) dependency injected private HibernateTitleDao titleDao; // a setter method to enable DI of the 'titleDao' instance variable public void setTitleDao(HibernateTitleDao titleDao) { this.titleDao = titleDao; } public void testLoadTitle() throws Exception { Title title = this.titleDao.loadTitle(new Long(10)); assertNotNull(title); } // specifies the Spring configuration to load for this test fixture protected String[] getConfigLocations() { return new String[] { "classpath:com/foo/daos.xml" }; } }
The file referenced by the getConfigLocations() method (i.e., "classpath:com/foo/daos.xml") looks like this:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- this bean will be injected into the HibernateTitleDaoTests class --> <bean id="titleDao" class="com.foo.dao.hibernate.HibernateTitleDao"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- dependencies elided for clarity --> </bean> </beans>
The AbstractDependencyInjectionSpringContextTests classes uses autowire by type. Thus if you have multiple bean definitions of the same type, you cannot rely on this approach for those particular beans. In that case, you can use the inherited applicationContext instance variable and perform explicit lookups using (for example) a call to applicationContext.getBean("titleDao").
If you don't want dependency injection applied to your test cases, simply don't declare any public setter methods. Alternatively, you can extend AbstractSpringContextTests - the root of the JUnit 3.8 integration testing support class hierarchy in the org.springframework.test package - which merely contains convenience methods to load Spring contexts and performs no Dependency Injection of the test fixture.
If, for whatever reason, you don't fancy having setter methods in your test fixtures, Spring can inject dependencies into protected fields. Find below a reworking of the previous example to use field level injection (the Spring XML configuration does not need to change, merely the test fixture).
public final class HibernateTitleDaoTests extends AbstractDependencyInjectionSpringContextTests { public HibernateTitleDaoTests() { // switch on field level injection setPopulateProtectedVariables(true); } // this instance will be (automatically) dependency injected protected HibernateTitleDao titleDao; public void testLoadTitle() throws Exception { Title title = this.titleDao.loadTitle(new Long(10)); assertNotNull(title); } // specifies the Spring configuration to load for this test fixture protected String[] getConfigLocations() { return new String[] { "classpath:com/foo/daos.xml" }; } }
In the case of field injection, there is no autowiring going on: the name of a protected instance variable is used as the lookup bean name in the configured Spring container.
AbstractTransactionalSpringContextTests depends on a PlatformTransactionManager bean being defined in the application context. The name doesn't matter due to the use of autowire by type.
Typically you will extend the subclass, AbstractTransactionalDataSourceSpringContextTests. This class also requires that a DataSource bean definition - again, with any name - be present in the application context. It creates a JdbcTemplate instance variable, that is useful for convenient querying, and provides handy methods to delete the contents of selected tables (remember that the transaction will roll back by default, so this is safe to do).
If you want a transaction to commit programmatically - unusual, but occasionally useful when you want a particular test to populate the database - you can call the setComplete() method inherited from AbstractTransactionalSpringContextTests. This will cause the transaction to commit instead of roll back. As an alternative, if you are developing against Java 5 or greater and extending AbstractAnnotationAwareTransactionalTests, you may annotate your test method with @Rollback(false) to achieve the same effect through configuration.
There is also the convenient ability to end a transaction before the test case ends, by calling the endTransaction() method. This will roll back the transaction by default and commit it only if setComplete() had previously been called. This functionality is useful if you want to test the behavior of 'disconnected' data objects, such as Hibernate-mapped entities that will be used in a web or remoting tier outside a transaction. Often, lazy loading errors are discovered only through UI testing; if you call endTransaction() you can ensure correct operation of the UI through your JUnit test suite.
When you extend the AbstractTransactionalDataSourceSpringContextTests class you will have access to the following protected instance variables:
applicationContext (a ConfigurableApplicationContext): inherited from the AbstractSingleSpringContextTests superclass. Use this to perform explicit bean lookup or to test the state of the context as a whole.
jdbcTemplate: inherited from AbstractTransactionalDataSourceSpringContextTests. Useful for querying to confirm state. For example, you might query before and after testing application code that creates an object and persists it using an ORM tool, to verify that the data appears in the database. (Spring will ensure that the query runs in the scope of the same transaction.) You will need to tell your ORM tool to 'flush' its changes for this to work correctly, for example using the flush() method on Hibernate's Session interface.
In addition to the aforementioned common annotations, the org.springframework.test.annotation package also contains an abstract JUnit TestCase class which provides annotation-driven integration testing support.
The AbstractAnnotationAwareTransactionalTests class extends AbstractTransactionalDataSourceSpringContextTests and makes text fixtures, which extend it, aware of a number of (Spring-specific) annotations. AbstractAnnotationAwareTransactionalTests supports all annotations listed in the common annotations section as well as Spring's @Transactional annotation for configuring explicit transactional semantics.
The org.springframework.test.jpa package provides support classes for tests based on the Java Persistence API (JPA).
AbstractJpaTests is a convenient support class for JPA-related tests, which offers the same contract as AbstractTransactionalDataSourceSpringContextTests and equally good performance, even when performing the instrumentation required by the JPA specification. Exposes an EntityManagerFactory and a shared EntityManager. Requires an EntityManagerFactory to be injected, plus the DataSource and JpaTransactionManager through the superclass.
AbstractAspectjJpaTests is a subclass of AbstractJpaTests that activates AspectJ load-time weaving and allows the ability to specify a custom location for AspectJ's aop.xml file.
The Spring TestContext Framework (located in the org.springframework.test.context package) provides generic, annotation-driven unit and integration testing support that is agnostic of the testing framework in use, for example JUnit 3.8, JUnit 4.4, TestNG 5.5, etc. The TestContext framework also places a great deal of importance on convention over configuration with reasonable defaults that can be overridden via annotation-based configuration.
In addition to generic testing infrastructure, the TestContext framework provides explicit support for JUnit 3.8, JUnit 4.4, and TestNG 5.5 in the form of abstract support classes. For JUnit 4.4, the framework also provides a custom Runner which allows one to write test classes that are not required to extend a particular class hierarchy.
The following section provides an overview of the internals of the TestContext framework. If you are only interested in using the framework and not necessarily interested in extending it with your own custom listeners, feel free to skip ahead to the configuration (context management, dependency injection, transaction management), support classes, and annotation support sections.
The core of the framework consists of the TestContext and TestContextManager classes and the TestExecutionListener interface. A TestContextManager is created on a per-test basis. The TestContextManager in turn manages a TestContext which is responsible for holding the context of the current test. The TestContextManager is also responsible for updating the state of the TestContext as the test progresses and delegating to TestExecutionListeners, which instrument the actual test execution (e.g., providing dependency injection, managing transactions, etc.). Consult the JavaDoc and the Spring test suite for further information and examples of various configurations.
TestContext: encapsulates the context in which a test is executed, agnostic of the actual testing framework in use.
TestContextManager: the main entry point into the Spring TestContext Framework, which is responsible for managing a single TestContext and signaling events to all registered TestExecutionListeners at well defined test execution points: test instance preparation, prior to any before methods of a particular testing framework, and after any after methods of a particular testing framework.
TestExecutionListener: defines a listener API for reacting to test execution events published by the TestContextManager with which the listener is registered.
Spring provides three TestExecutionListener implementations which are configured by default (via the @TestExecutionListeners annotation): DependencyInjectionTestExecutionListener, DirtiesContextTestExecutionListener, and TransactionalTestExecutionListener, which provide support for dependency injection of the test instance, handling of the @DirtiesContext annotation, and transactional test execution support with default rollback semantics, respectively.
The following three sections explain how to configure the TestContext framework via annotations and provide working examples of how to actually write unit and integration tests with the framework.
Each TestContext provides context management and caching support for the test instance for which it is responsible. Test instances do not automatically receive access to the configured ApplicationContext; however, if a test class implements the ApplicationContextAware interface, a reference to the ApplicationContext will be supplied to the test instance (provided the DependencyInjectionTestExecutionListener has been configured, which is the default). Note that AbstractJUnit38SpringContextTests, AbstractJUnit4SpringContextTests, and AbstractTestNGSpringContextTests already implement ApplicationContextAware and therefore provide this functionality out-of-the-box.
In contrast to the JUnit 3.8 legacy support, test classes which use the TestContext framework do not need to override any protected instance methods to configure their application context. Rather, configuration is achieved merely by declaring the @ContextConfiguration annotation at the class level. If your test class does not explicitly declare any application context resource locations, the configured ContextLoader will determine how and whether or not to load a context from a default set of locations. For example, GenericXmlContextLoader - which is the default ContextLoader - will generate a default location based on the name of the test class. If your class is named com.example.MyTest, GenericXmlContextLoader will load your application context from "classpath:/com/example/MyTest-context.xml".
package com.example; @RunWith(SpringJUnit4ClassRunner.class) // ApplicationContext will be loaded from "classpath:/com/example/MyTest-context.xml" @ContextConfiguration public class MyTest { // class body... }
If the default location does not suit your needs, you are free to explicitly configure the locations attribute of @ContextConfiguration (see code listing below) with an array containing the resource locations of XML configuration metadata (assuming an XML-capable ContextLoader has been configured) - typically on the classpath - used to configure the application. This will be the same, or nearly the same, as the list of configuration locations specified in web.xml or other deployment configuration. As an alternative you may choose to implement and configure your own custom ContextLoader.
@RunWith(SpringJUnit4ClassRunner.class) // ApplicationContext will be loaded from "/applicationContext.xml" and "/applicationContext-test.xml" // in the root of the classpath @ContextConfiguration(locations={"/applicationContext.xml", "/applicationContext-test.xml"}) public class MyTest { // class body... }
@ContextConfiguration also supports a boolean inheritLocations attribute which denotes whether or not resource locations from superclasses should be inherited. The default value is true, which means that an annotated class will inherit the resource locations defined by an annotated superclass. Specifically, the resource locations for an annotated class will be appended to the list of resource locations defined by an annotated superclass. Thus, subclasses have the option of extending the list of resource locations. In the following example, the ApplicationContext for ExtendedTest will be loaded from "/base-context.xml" and "/extended-context.xml", in that order. Beans defined in "/extended-context.xml" may therefore override those defined in "/base-context.xml".
@RunWith(SpringJUnit4ClassRunner.class) // ApplicationContext will be loaded from "/base-context.xml" in the root of the classpath @ContextConfiguration(locations={"/base-context.xml"}) public class BaseTest { // class body... } // ApplicationContext will be loaded from "/base-context.xml" and "/extended-context.xml" // in the root of the classpath @ContextConfiguration(locations={"/extended-context.xml"}) public class ExtendedTest extends BaseTest { // class body... }
If inheritLocations is set to false, the resource locations for the annotated class will shadow and effectively replace any resource locations defined by a superclass.
By default, once loaded, the configured ApplicationContext will be reused for each test. Thus the setup cost will be incurred only once (per test fixture), and subsequent test execution will be much faster. In the unlikely case that a test may dirty the application context, requiring reloading - for example, by changing a bean definition or the state of an application object - you may annotate your test method with @DirtiesContext (assuming DirtiesContextTestExecutionListener has been configured, which is the default) to cause the test fixture to reload the configurations and rebuild the application context before executing the next test.
When you configure the DependencyInjectionTestExecutionListener - which is configured by default - via the @TestExecutionListeners annotation, the dependencies of your test instances will be injected from beans in the application context you configured via @ContextConfiguration by Setter Injection, Field Injection, or both, depending on which annotations you choose and whether you place them on setter methods or fields. For consistency with annotation support in Spring 2.5, you may choose either Spring's @Autowired annotation or the @Resource annotation from JSR 250. The semantics for both are consistent throughout the Spring Framework. For example, if you prefer autowiring by type, annotate your setter methods or fields with @Autowired. On the other hand, if you prefer to have your dependencies injected by name, annotate your setter methods or fields with @Resource.
Tip | |
---|---|
The TestContext framework does not instrument the manner in which a test instance is instantiated. Thus the use of @Autowired for constructors has no effect for test classes. |
Since @Autowired performs autowiring by type, if you have multiple bean definitions of the same type, you cannot rely on this approach for those particular beans. In that case, you can use @Resource for injection by name. Alternatively, if your test class implements ApplicationContextAware, you can directly access the ApplicationContext supplied to your test and perform an explicit lookup using (for example) a call to applicationContext.getBean("titleDao").
If you don't want dependency injection applied to your test instances, simply don't annotate any fields or setter methods with @Autowired or @Resource. Alternatively, you can disable dependency injection altogether by explicitly configuring your class with @TestExecutionListeners and omitting DependencyInjectionTestExecutionListener.class from the list of listeners.
Consider the scenario where we have a class, HibernateTitleDao (as outlined in the common goals section). First, let's look at a JUnit 4.4 based implementation of the test class itself which uses @Autowired for field injection (we will look at the application context configuration after all sample code listings). Note: the dependency injection behavior in the following code listings is not in any way specific to JUnit 4.4. The same DI techniques can be used in conjunction with any testing framework.
@RunWith(SpringJUnit4ClassRunner.class) // specifies the Spring configuration to load for this test fixture @ContextConfiguration(locations={"daos.xml"}) public final class HibernateTitleDaoTests { // this instance will be dependency injected by type @Autowired private HibernateTitleDao titleDao; public void testLoadTitle() throws Exception { Title title = this.titleDao.loadTitle(new Long(10)); assertNotNull(title); } }
Alternatively, we can configure the class to use @Autowired for setter injection.
@RunWith(SpringJUnit4ClassRunner.class) // specifies the Spring configuration to load for this test fixture @ContextConfiguration(locations={"daos.xml"}) public final class HibernateTitleDaoTests { // this instance will be dependency injected by type private HibernateTitleDao titleDao; @Autowired public void setTitleDao(HibernateTitleDao titleDao) { this.titleDao = titleDao; } public void testLoadTitle() throws Exception { Title title = this.titleDao.loadTitle(new Long(10)); assertNotNull(title); } }
Now let's take a look at an example using @Resource for field injection.
@RunWith(SpringJUnit4ClassRunner.class) // specifies the Spring configuration to load for this test fixture @ContextConfiguration(locations={"daos.xml"}) public final class HibernateTitleDaoTests { // this instance will be dependency injected by name @Resource private HibernateTitleDao titleDao; public void testLoadTitle() throws Exception { Title title = this.titleDao.loadTitle(new Long(10)); assertNotNull(title); } }
Finally, here is an example using @Resource for setter injection.
@RunWith(SpringJUnit4ClassRunner.class) // specifies the Spring configuration to load for this test fixture @ContextConfiguration(locations={"daos.xml"}) public final class HibernateTitleDaoTests { // this instance will be dependency injected by name private HibernateTitleDao titleDao; @Resource public void setTitleDao(HibernateTitleDao titleDao) { this.titleDao = titleDao; } public void testLoadTitle() throws Exception { Title title = this.titleDao.loadTitle(new Long(10)); assertNotNull(title); } }
The above code listings use the same XML context file referenced by the @ContextConfiguration annotation (i.e., "daos.xml") which looks like this:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- this bean will be injected into the HibernateTitleDaoTests class --> <bean id="titleDao" class="com.foo.dao.hibernate.HibernateTitleDao"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- dependencies elided for clarity --> </bean> </beans>
In the TestContext framework, transactions are managed by the TransactionalTestExecutionListener, which is configured via the @TestExecutionListeners annotation by default, even if you do not explicitly declare @TestExecutionListeners on your test class. To enable support for transactions, however, you must provide a PlatformTransactionManager bean in the application context loaded via @ContextConfiguration semantics. In addition, you must declare @Transactional either at the class or method level.
For class-level transaction configuration (i.e., setting the bean name for the transaction manager and the default rollback flag), see the @TransactionConfiguration entry in the TestContext framework annotation support section.
There are several options for configuring transactions for individual test methods. If transactions are not enabled for the entire test class, methods may be explicitly annotated with @Transactional. Similarly, if transactions are enabled for the entire test class, methods may be explicitly flagged not to run within a transaction by annotating them with @NotTransactional. To control whether or not a transaction should commit for a particular test method, you may use the @Rollback annotation to override the class-level default rollback setting.
Note that AbstractTransactionalJUnit38SpringContextTests, AbstractTransactionalJUnit4SpringContextTests, and AbstractTransactionalTestNGSpringContextTests are pre-configured for transactional support at the class level.
You will occasionally find that you need to execute certain code before or after a transactional test method but outside the transactional context, for example to verify the initial database state prior to execution of your test or to verify expected transactional commit behavior after test execution (e.g., if the test was configured not to roll back the transaction). TransactionalTestExecutionListener supports the @BeforeTransaction and @AfterTransaction annotations exactly for such scenarios. Simply annotate any public void method in your test class with one of these annotations, and the TransactionalTestExecutionListener will ensure that your before transaction method or after transaction method is executed at the appropriate time.
Tip | |
---|---|
Any before methods (e.g., methods annotated with JUnit 4's @Before) and any after methods (e.g., methods annotated with JUnit 4's @After) will be executed within a transaction. In addition, methods annotated with @BeforeTransaction or @AfterTransaction will naturally not be executed for tests annotated with @NotTransactional. |
The following JUnit 4 based example displays a fictitious integration testing scenario highlighting several of the transaction-related annotations. Consult the TestContext framework annotation support section of the reference manual for further information and configuration examples.
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @TransactionConfiguration(transactionManager="txMgr", defaultRollback=false) @Transactional public class FictitiousTransactionalTest { @BeforeTransaction public void verifyInitialDatabaseState() { // logic to verify the initial state before a transaction is started } @Before public void setUpTestDataWithinTransaction() { // set up test data within the transaction } @Test // overrides the class-level defaultRollback setting @Rollback(true) public void modifyDatabaseWithinTransaction() { // logic which uses the test data and modifies database state } @After public void tearDownWithinTransaction() { // execute "tear down" logic within the transaction } @AfterTransaction public void verifyFinalDatabaseState() { // logic to verify the final state after transaction has rolled back } @Test @NotTransactional public void performNonDatabaseRelatedAction() { // logic which does not modify database state } }
The org.springframework.test.context.junit38 package provides support classes for JUnit 3.8 based test cases.
AbstractJUnit38SpringContextTests:
Abstract TestCase which integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a JUnit 3.8 environment. When you extend the AbstractJUnit38SpringContextTests class you will have access to the following protected instance variables:
applicationContext: use this to perform explicit bean lookups or to test the state of the context as a whole.
AbstractTransactionalJUnit38SpringContextTests:
Abstract transactional extension of AbstractJUnit38SpringContextTests that also adds some convenience functionality for JDBC access. Expects a javax.sql.DataSource bean and a PlatformTransactionManager bean to be defined in the ApplicationContext. When you extend the AbstractTransactionalJUnit38SpringContextTests class you will have access to the following protected instance variables:
applicationContext: inherited from the AbstractJUnit38SpringContextTests superclass. Use this to perform explicit bean lookups or to test the state of the context as a whole.
simpleJdbcTemplate: useful for querying to confirm state. For example, you might query before and after testing application code that creates an object and persists it using an ORM tool, to verify that the data appears in the database. (Spring will ensure that the query runs in the scope of the same transaction.) You will need to tell your ORM tool to 'flush' its changes for this to work correctly, for example using the flush() method on Hibernate's Session interface.
The org.springframework.test.context.junit4 package provides support classes for JUnit 4.4 based test cases.
AbstractJUnit4SpringContextTests:
Abstract base test class which integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a JUnit 4.4 environment.
When you extend AbstractJUnit4SpringContextTests you will have access to the following protected instance variables:
applicationContext: use this to perform explicit bean lookups or to test the state of the context as a whole.
AbstractTransactionalJUnit4SpringContextTests:
Abstract transactional extension of AbstractJUnit4SpringContextTests that also adds some convenience functionality for JDBC access. Expects a javax.sql.DataSource bean and a PlatformTransactionManager bean to be defined in the ApplicationContext.
When you extend AbstractTransactionalJUnit4SpringContextTests you will have access to the following protected instance variables:
applicationContext: inherited from the AbstractJUnit4SpringContextTests superclass. Use this to perform explicit bean lookups or to test the state of the context as a whole.
simpleJdbcTemplate: useful for querying to confirm state. For example, you might query before and after testing application code that creates an object and persists it using an ORM tool, to verify that the data appears in the database. (Spring will ensure that the query runs in the scope of the same transaction.) You will need to tell your ORM tool to 'flush' its changes for this to work correctly, for example using the flush() method on Hibernate's Session interface.
Tip | |
---|---|
These classes serve only as a convenience for extension. If you do not wish for your test classes to be tied to a Spring-specific class hierarchy - for example, if you wish to directly extend the class you are testing - you may configure your own custom test classes by using @RunWith(SpringJUnit4ClassRunner.class), @ContextConfiguration, @TestExecutionListeners, etc. |
The Spring TestContext Framework offers full integration with JUnit 4.4 via a custom runner. By annotating test classes with @Runwith(SpringJUnit4ClassRunner.class), developers can implement standard JUnit 4.4 unit and integration tests and simultaneously reap the benefits of the TestContext framework such as support for loading application contexts, dependency injection of test instances, transactional test method execution, etc. The following code listing displays the minimal requirements for configuring a test class to run with the custom Spring Runner. Note that @TestExecutionListeners has been configured with an empty list in order to disable the default listeners, which would otherwise require that an ApplicationContext be configured via @ContextConfiguration.
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({})
public class SimpleTest {
@Test
public void testMethod() {
// execute test logic...
}
}
The org.springframework.test.context.testng package provides support classes for TestNG based test cases.
AbstractTestNGSpringContextTests:
Abstract base test class which integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a TestNG environment.
When you extend AbstractTestNGSpringContextTests you will have access to the following protected instance variables:
applicationContext: use this to perform explicit bean lookups or to test the state of the context as a whole.
AbstractTransactionalTestNGSpringContextTests:
Abstract transactional extension of AbstractTestNGSpringContextTests that adds some convenience functionality for JDBC access. Expects a javax.sql.DataSource bean and a PlatformTransactionManager bean to be defined in the ApplicationContext.
When you extend AbstractTransactionalTestNGSpringContextTests you will have access to the following protected instance variables:
applicationContext: inherited from the AbstractTestNGSpringContextTests superclass. Use this to perform explicit bean lookups or to test the state of the context as a whole.
simpleJdbcTemplate: useful for querying to confirm state. For example, you might query before and after testing application code that creates an object and persists it using an ORM tool, to verify that the data appears in the database. (Spring will ensure that the query runs in the scope of the same transaction.) You will need to tell your ORM tool to 'flush' its changes for this to work correctly, for example using the flush() method on Hibernate's Session interface.
Tip | |
---|---|
These classes serve only as a convenience for extension. If you do not wish for your test classes to be tied to a Spring-specific class hierarchy - for example, if you wish to directly extend the class you are testing - you may configure your own custom test classes by using @ContextConfiguration, @TestExecutionListeners, etc. and by manually instrumenting your test class with a TestContextManager. See the source code of AbstractTestNGSpringContextTests for an example of how to instrument your test class. |
The Spring TestContext Framework supports all annotations as outlined in the common annotations section. The following annotations, however, are only supported when used in conjunction with JUnit (e.g., with the SpringJUnit4ClassRunner or the JUnit 3.8 and JUnit 4.4 support classes.
@IfProfileValue
@ProfileValueSourceConfiguration
@ExpectedException
Using Spring's @ExpectedException annotation in conjunction with JUnit 4's @Test(expected=...) configuration would lead to an unresolvable conflict. Developers must therefore choose one or the other when integrating with JUnit 4, in which case it is generally preferable to use the explicit JUnit 4 configuration.
@Timed
Spring's @Timed annotation has different semantics than JUnit 4's @Test(timeout=...) support. Specifically, due to the manner in which JUnit 4 handles test execution timeouts (i.e., by executing the test method in a separate Thread), one can not use JUnit's @Test(timeout=...) configuration on a test method which is executed in a transactional context. Therefore, if you wish to configure a test method to be both timed and transactional, you must use a combination of Spring's @Timed and @Transactional annotations. It also worth noting that @Test(timeout=...) times only the execution of the test method itself and preemptively fails the test if the test takes too long; whereas, @Timed times the total test execution time (including set up and tear down operations as well as repetitions) and does not preemptively fail the test.
@Repeat
The following non-test-specific annotations are also supported by the Spring TestContext Framework with their standard semantics.
@Autowired
@Qualifier
@Resource (javax.annotation) if JSR-250 is present
@PersistenceContext (javax.persistence) if JPA is present
@PersistenceUnit (javax.persistence) if JPA is present
@Required
@Transactional
The following list includes all annotations specific to the Spring TestContext Framework. Refer to the respective JavaDoc for further information, including default attribute values, etc.
@ContextConfiguration
Defines class-level metadata which is used to determine how to load and configure an ApplicationContext. Specifically, @ContextConfiguration defines the application context resource locations to load as well as the ContextLoader strategy to use for loading the context.
@ContextConfiguration(locations={"example/test-context.xml"}, loader=CustomContextLoader.class)
public class CustomConfiguredApplicationContextTests {
// class body...
}
Note: @ContextConfiguration provides support for inherited resource locations by default. See the Context management and caching section and JavaDoc for an example and further details.
@TestExecutionListeners
Defines class-level metadata for configuring which TestExecutionListeners should be registered with a TestContextManager. Typically, @TestExecutionListeners will be used in conjunction with @ContextConfiguration.
@ContextConfiguration
@TestExecutionListeners({CustomTestExecutionListener.class, AnotherTestExecutionListener.class})
public class CustomTestExecutionListenerTests {
// class body...
}
Note: @TestExecutionListeners provides support for inherited listeners by default. See the JavaDoc for an example and further details.
@TransactionConfiguration
Defines class-level metadata for configuring transactional tests. Specifically, the bean name of the PlatformTransactionManager that is to be used to drive transactions can be explicitly configured if the bean name of the desired PlatformTransactionManager is not "transactionManager". In addition, the defaultRollback flag can optionally be changed to false. Typically, @TransactionConfiguration will be used in conjunction with @ContextConfiguration.
@ContextConfiguration
@TransactionConfiguration(transactionManager="txMgr", defaultRollback=false)
public class CustomConfiguredTransactionalTests {
// class body...
}
@BeforeTransaction
Indicates that the annotated public void method should be executed before a transaction is started for test methods configured to run within a transaction via the @Transactional annotation.
@BeforeTransaction
public void beforeTransaction() {
// logic to be executed before a transaction is started
}
@AfterTransaction
Indicates that the annotated public void method should be executed after a transaction has been ended for test methods configured to run within a transaction via the @Transactional annotation.
@AfterTransaction
public void afterTransaction() {
// logic to be executed after a transaction has ended
}
The PetClinic sample application included with the full Spring distribution illustrates several features of the Spring TestContext Framework in a JUnit 4.4 environment. Most test functionality is included in the AbstractClinicTests, for which a partial listing is shown below:
@ContextConfiguration public abstract class AbstractClinicTests extends AbstractTransactionalJUnit4SpringContextTests { @Autowired protected Clinic clinic; @Test public void getVets() { Collection<Vet> vets = this.clinic.getVets(); assertEquals("JDBC query must show the same number of vets", super.countRowsInTable("VETS"), vets.size()); Vet v1 = EntityUtils.getById(vets, Vet.class, 2); assertEquals("Leary", v1.getLastName()); assertEquals(1, v1.getNrOfSpecialties()); assertEquals("radiology", (v1.getSpecialties().get(0)).getName()); // ... } // ... }
Notes:
This test case extends the AbstractTransactionalJUnit4SpringContextTests class, from which it inherits configuration for Dependency Injection (via the DependencyInjectionTestExecutionListener) and transactional behavior (via the TransactionalTestExecutionListener).
The clinic instance variable - the application object being tested - is set by Dependency Injection via @Autowired semantics.
The testGetVets() method illustrates how the inherited countRowsInTable() method can be used to easily verify the number of rows in a given table, thus testing correct behavior of the application code being tested. This allows for stronger tests and lessens dependency on the exact test data. For example, you can add additional rows in the database without breaking tests.
Like many integration tests using a database, most of the tests in AbstractClinicTests depend on a minimum amount of data already in the database before the test cases run. You might, however, choose to populate the database in your test cases also - again, within the same transaction.
The PetClinic application supports three data access technologies - JDBC, Hibernate, and JPA. By declaring @ContextConfiguration without any specific resource locations, the AbstractClinicTests class will have its application context loaded from the default location, "AbstractClinicTests-context.xml", which declares a common DataSource. Subclasses specify additional context locations which must declare a PlatformTransactionManager and a concrete implementation of Clinic.
For example, the Hibernate implementation of the PetClinic tests contains the following implementation. Note that for this example, HibernateClinicTests does not contain a single line of code: we only need to declare @ContextConfiguration, and the tests are inherited from AbstractClinicTests. Since @ContextConfiguration is declared without any specific resource locations, the Spring TestContext Framework will load an application context from all the beans defined in "AbstractClinicTests-context.xml" (i.e., the inherited locations) and "HibernateClinicTests-context.xml", with "HibernateClinicTests-context.xml" possibly overriding beans defined in "AbstractClinicTests-context.xml".
@ContextConfiguration
public class HibernateClinicTests extends AbstractClinicTests { }
As you can see in the PetClinic application, the Spring configuration is split across multiple files. As is typical of large scale applications, configuration locations will often be specified in a common base class for all application-specific integration tests. Such a base class may also add useful instance variables - populated by Dependency Injection, naturally - such as a HibernateTemplate, in the case of an application using Hibernate.
As far as possible, you should have exactly the same Spring configuration files in your integration tests as in the deployed environment. One likely point of difference concerns database connection pooling and transaction infrastructure. If you are deploying to a full-blown application server, you will probably use its connection pool (available through JNDI) and JTA implementation. Thus in production you will use a JndiObjectFactoryBean for the DataSource and JtaTransactionManager. JNDI and JTA will not be available in out-of-container integration tests, so you should use a combination like the Commons DBCP BasicDataSource and DataSourceTransactionManager or HibernateTransactionManager for them. You can factor out this variant behavior into a single XML file, having the choice between application server and 'local' configuration separated from all other configuration, which will not vary between the test and production environments. In addition, it is advisable to use properties files for connection settings: see the PetClinic application for an example.
This section contains links to further resources about testing in general.
The JUnit homepage. The Spring Framework's unit test suite is written using JUnit 3.8 as the testing framework.
The TestNG homepage. TestNG is a testing framework inspired by JUnit 3.8 with added support for Java 5 annotations, test groups, data-driven testing, distributed testing, etc.
The Mock Objects homepage. About Mock Objects, a technique for improving the design of code within Test-Driven Development.
The EasyMock homepage. The Spring Framework uses EasyMock extensively in it's test suite.
The JMock homepage. JMock is a library that supports test-driven development of Java code with mock objects.
The DbUnit homepage. DbUnit is a JUnit extension (also usable with Ant) targeted for database-driven projects that, among other things, puts your database into a known state between test runs.
The Grinder homepage. The Grinder is a Java load-testing framework.