10. Testing

10.1 Introduction to Spring Testing

Testing is an integral part of enterprise software development. This chapter focuses on the value-add of the IoC principle to unit testing and on the benefits of the Spring Framework's support for integration testing. (A thorough treatment of testing in the enterprise is beyond the scope of this reference manual.)

10.2 Unit Testing

Dependency Injection should make your code less dependent on the container than it would be with traditional Java EE development. The POJOs that make up 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 other valuable testing techniques) to test your code in isolation. If you follow the architecture recommendations for Spring, the resulting clean layering and componentization of your codebase will facilitate easier unit testing. For example, you can test service layer objects by stubbing or mocking DAO or Repository interfaces, without needing to access persistent data while running unit tests.

True unit tests typically run extremely quickly, as there is no runtime infrastructure to set up. Emphasizing true unit tests as part of your development methodology will boost your productivity. You may 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.

10.2.1 Mock Objects

10.2.1.1 JNDI

The org.springframework.mock.jndi package contains an implementation of the JNDI SPI, which you can use to set 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 Java EE container, you can reuse both application code and configuration in testing scenarios without modification.

10.2.1.2 Servlet API

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 such as EasyMock or existing Servlet API mock objects such as MockObjects.

10.2.1.3 Portlet API

The org.springframework.mock.web.portlet package contains a set of Portlet API mock objects, targeted at usage with Spring's Portlet MVC framework.

10.2.2 Unit Testing support Classes

10.2.2.1 General utilities

The org.springframework.test.util package contains ReflectionTestUtils, which is a collection of reflection-based utility methods. Developers use these methods in unit and integration testing scenarios in which they need 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 that condone 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, @Inject, and @Resource, which provides dependency injection for private or protected fields, setter methods, and configuration methods.

10.2.2.2 Spring MVC

The org.springframework.test.web package contains ModelAndViewAssert, which you can use in combination with JUnit, TestNG, or any other testing framework for unit tests dealing with Spring MVC ModelAndView objects.

[Tip]Unit testing Spring MVC Controllers

To test your Spring MVC Controllers, use ModelAndViewAssert combined with MockHttpServletRequest, MockHttpSession, and so on from the org.springframework.mock.web package.

10.3 Integration Testing

10.3.1 Overview

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 spring-test module. The name of the actual JAR file might include the release version and might also be in the long org.springframework.test form, depending on where you get it from (see the section on Dependency Management for an explanation). This library includes the org.springframework.test package, which contains valuable classes for integration testing with a Spring container. This testing does not rely on an application server or other deployment environment. Such tests are slower to run than unit tests but much faster than the equivalent Cactus tests or remote tests that rely on deployment to an application server.

In Spring 2.5 and later, unit and integration testing support is provided in the form of the annotation-driven Spring TestContext Framework. The TestContext framework is agnostic of the actual testing framework in use, thus allowing instrumentation of tests in various environments including JUnit, TestNG, and so on.

[Warning]JUnit 3.8 support is deprecated

As of Spring 3.0, the legacy JUnit 3.8 base class hierarchy (i.e., AbstractDependencyInjectionSpringContextTests, AbstractTransactionalDataSourceSpringContextTests, etc.) is officially deprecated and will be removed in a later release. Any test classes based on this code should be migrated to the Spring TestContext Framework.

As of Spring 3.1, the JUnit 3.8 base classes in the Spring TestContext Framework (i.e., AbstractJUnit38SpringContextTests and AbstractTransactionalJUnit38SpringContextTests) and @ExpectedException have been officially deprecated and will be removed in a later release. Any test classes based on this code should be migrated to the JUnit 4 or TestNG support provided by the Spring TestContext Framework. Similarly, any test methods annotated with @ExpectedException should be modified to use the built-in support for expected exceptions in JUnit and TestNG.

10.3.2 Goals of Integration Testing

Spring's integration testing support has the following primary goals:

The next few sections describe each goal and provide links to implementation and configuration details.

10.3.2.1 Context management and caching

The Spring TestContext Framework provides consistent loading of Spring ApplicationContexts and caching of those contexts. Support for the caching of loaded contexts is important, because startup time can become an issue — not because of the overhead of Spring itself, but because the objects instantiated by the Spring container take time to instantiate. For example, a project with 50 to 100 Hibernate mapping files might take 10 to 20 seconds to load the mapping files, and incurring that cost before running every test in every test fixture leads to slower overall test runs that could reduce productivity.

Test classes can provide either an array containing the resource locations of XML configuration metadata — typically in the classpath — or an array containing @Configuration classes that is used to configure the application. These locations or classes are the same as or similar to those specified in web.xml or other deployment configuration files.

By default, once loaded, the configured ApplicationContext is reused for each test. Thus the setup cost is incurred only once (per test suite), and subsequent test execution is much faster. In this context, the term test suite means all tests run in the same JVM — for example, all tests run from an Ant or Maven build for a given project or module. In the unlikely case that a test corrupts the application context and requires reloading — for example, by modifying a bean definition or the state of an application object — the TestContext framework can be configured to reload the configuration and rebuild the application context before executing the next test.

See context management and caching with the TestContext framework.

10.3.2.2 Dependency Injection of test fixtures

When the TestContext framework loads your application context, it can optionally configure instances of your test classes via Dependency Injection. This provides a convenient mechanism for setting up test fixtures using preconfigured 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, HibernateTitleRepository, that performs data access logic for a Title domain entity. We want to write integration tests that test the following areas:

  • The Spring configuration: basically, is everything related to the configuration of the HibernateTitleRepository 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 HibernateTitleRepository: does the configured instance of this class perform as anticipated?

See dependency injection of test fixtures with the TestContext framework.

10.3.2.3 Transaction management

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 or modifying persistent data — cannot be performed (or verified) outside a transaction.

The TestContext framework addresses this issue. By default, the framework will 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 configured 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 TestContext framework can be instructed to cause the transaction to commit instead of roll back via the @TransactionConfiguration and @Rollback annotations.

See transaction management with the TestContext framework.

10.3.2.4 Support classes for integration testing

The Spring TestContext Framework provides several abstract support classes that simplify the writing of integration tests. These base test classes provide well-defined hooks into the testing framework as well as convenient instance variables and methods, which enable you to access:

  • The ApplicationContext, for performing explicit bean lookups or testing the state of the context as a whole.

  • A SimpleJdbcTemplate, for executing SQL statements to query the database. Such queries can be used to confirm database state both prior to and after execution of database-related application code, and Spring ensures that such queries run in the scope of the same transaction as the application code. When used in conjunction with an ORM tool, be sure to avoid false positives.

In addition, you may want to create your own custom, application-wide superclass with instance variables and methods specific to your project.

See support classes for the TestContext framework.

10.3.3 JDBC Testing Support

The org.springframework.test.jdbc package contains SimpleJdbcTestUtils, which is a collection of JDBC related utility functions intended to simplify standard database testing scenarios. Note that AbstractTransactionalJUnit4SpringContextTests and AbstractTransactionalTestNGSpringContextTests provide convenience methods which delegate to SimpleJdbcTestUtils internally.

10.3.4 Annotations

10.3.4.1 Spring Testing Annotations

The Spring Framework provides the following set of Spring-specific annotations that you can use in your unit and integration tests in conjunction with the TestContext framework. Refer to the respective Javadoc for further information, including default attribute values, attribute aliases, and so on.

  • @ContextConfiguration

    Defines class-level metadata that is used to determine how to load and configure an ApplicationContext for test classes. Specifically, @ContextConfiguration declares either the application context resource locations or the @Configuration classes (but not both) to load as well as the ContextLoader strategy to use for loading the context. Note, however, that you typically do not need to explicitly configure the loader since the default loader supports either resource locations or configuration classes.

    @ContextConfiguration(locations="example/test-context.xml", loader=CustomContextLoader.class)
    public class XmlApplicationContextTests {
        // class body...
    }
    @ContextConfiguration(classes=MyConfig.class)
    public class ConfigClassApplicationContextTests {
        // class body...
    }
    [Note]Note

    @ContextConfiguration provides support for inheriting resource locations or configuration classes declared by superclasses by default.

    See Context management and caching and Javadoc for examples and further details.

  • @ActiveProfiles

    A class-level annotation that is used to declare which bean definition profiles should be active when loading an ApplicationContext for test classes.

    @ContextConfiguration
    @ActiveProfiles("dev")
    public class DeveloperTests {
        // class body...
    }
    @ContextConfiguration
    @ActiveProfiles({"dev", "integration"})
    public class DeveloperIntegrationTests {
        // class body...
    }
    [Note]Note

    @ActiveProfiles provides support for inheriting active bean definition profiles declared by superclasses classes by default.

    See Context configuration with environment profiles and the Javadoc for @ActiveProfiles for examples and further details.

  • @DirtiesContext

    Indicates that the underlying Spring ApplicationContext has been dirtied (i.e., modified or corrupted in some manner) during the execution of a test and should be closed, regardless of whether the test passed. @DirtiesContext is supported in the following scenarios:

    • After the current test class, when declared on a class with class mode set to AFTER_CLASS, which is the default class mode.

    • After each test method in the current test class, when declared on a class with class mode set to AFTER_EACH_TEST_METHOD.

    • After the current test, when declared on a method.

    Use this annotation if a test has modified the context (for example, by replacing a bean definition). Subsequent tests are supplied a new context.

    With JUnit 4.5+ or TestNG you can use @DirtiesContext as both a class-level and method-level annotation within the same test class. In such scenarios, the ApplicationContext is marked as dirty after any such annotated method as well as after the entire class. If the ClassMode is set to AFTER_EACH_TEST_METHOD, the context is marked dirty after each test method in the class.

    @DirtiesContext
    public class ContextDirtyingTests {
        // some tests that result in the Spring container being dirtied
    }
    @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
    public class ContextDirtyingTests {
        // some tests that result in the Spring container being dirtied
    }
    @DirtiesContext
    @Test
    public void testProcessWhichDirtiesAppCtx() {
        // some logic that results in the Spring container being dirtied
    }

    When an application context is marked dirty, it is removed from the testing framework's cache and closed; thus the underlying Spring container is rebuilt for any subsequent test that requires a context with the same set of resource locations.

  • @TestExecutionListeners

    Defines class-level metadata for configuring which TestExecutionListeners should be registered with the TestContextManager. Typically, @TestExecutionListeners is used in conjunction with @ContextConfiguration.

    @ContextConfiguration
    @TestExecutionListeners({CustomTestExecutionListener.class, AnotherTestExecutionListener.class})
    public class CustomTestExecutionListenerTests {
        // class body...
    }

    @TestExecutionListeners supports 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, you can change the defaultRollback flag to false. Typically, @TransactionConfiguration is used in conjunction with @ContextConfiguration.

    @ContextConfiguration
    @TransactionConfiguration(transactionManager="txMgr", defaultRollback=false)
    public class CustomConfiguredTransactionalTests {
        // class body...
    }
    [Note]Note

    If the default conventions are sufficient for your test configuration, you can avoid using @TransactionConfiguration altogether. In other words, if your transaction manager bean is named "transactionManager" and if you want transactions to roll back automatically, there is no need to annotate your test class with @TransactionConfiguration.

  • @Rollback

    Indicates whether the transaction for the annotated test method should be rolled back after the test method has completed. If true, the transaction is rolled back; otherwise, the transaction is committed. Use @Rollback to override the default rollback flag configured at the class level.

    @Rollback(false)
    @Test
    public void testProcessWithoutRollback() {
        // ...
    }
  • @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 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
    }
  • @NotTransactional

    The presence of this annotation indicates that the annotated test method must not execute in a transactional context.

    @NotTransactional
    @Test
    public void testProcessWithoutTransaction() {
        // ...
    }
    [Warning]@NotTransactional is deprecated

    As of Spring 3.0, @NotTransactional is deprecated in favor of moving the non-transactional test method to a separate (non-transactional) test class or to a @BeforeTransaction or @AfterTransaction method. As an alternative to annotating an entire class with @Transactional, consider annotating individual methods with @Transactional; doing so allows a mix of transactional and non-transactional methods in the same test class without the need for using @NotTransactional.

10.3.4.2 Standard Annotation Support

The following annotations are supported with standard semantics for all configurations of the Spring TestContext Framework. Note that these annotations are not specific to tests and can be used anywhere in the Spring Framework.

  • @Autowired

  • @Qualifier

  • @Resource (javax.annotation) if JSR-250 is present

  • @Inject (javax.inject) if JSR-330 is present

  • @Named (javax.inject) if JSR-330 is present

  • @PersistenceContext (javax.persistence) if JPA is present

  • @PersistenceUnit (javax.persistence) if JPA is present

  • @Required

  • @Transactional

10.3.4.3 Spring JUnit Testing Annotations

The following annotations are only supported when used in conjunction with the SpringJUnit4ClassRunner or the JUnit support classes.

  • @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 is enabled. This annotation can be applied to an entire class or to individual methods. Class-level usage overrides method-level usage.

    @IfProfileValue(name="java.vendor", value="Sun Microsystems Inc.")
    @Test
    public void testProcessWhichRunsOnlyOnSunJvm() {
        // some logic that should run only on Java VMs from Sun Microsystems
    }

    Alternatively, you can configure @IfProfileValue 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"})
    @Test
    public void testProcessWhichRunsForUnitOrIntegrationTestGroups() {
        // some logic that should run only for unit and integration test groups
    }
  • @ProfileValueSourceConfiguration

    Class-level annotation that specifies what type of ProfileValueSource to use when retrieving profile values configured through the @IfProfileValue annotation. If @ProfileValueSourceConfiguration is not declared for a test, SystemProfileValueSource is used by default.

    @ProfileValueSourceConfiguration(CustomProfileValueSource.class)
    public class CustomProfileValueSourceTests {
        // class body...
    }
  • @Timed

    Indicates that the annotated test method must finish execution in a specified time period (in milliseconds). If the text execution time exceeds the specified time period, the test fails.

    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
    }

    Spring's @Timed annotation has different semantics than JUnit's @Test(timeout=...) support. Specifically, due to the manner in which JUnit handles test execution timeouts (that is, by executing the test method in a separate Thread), @Test(timeout=...) applies to each iteration in the case of repetitions and preemptively fails the test if the test takes too long. Spring's @Timed, on the other hand, times the total test execution time (including all repetitions) and does not preemptively fail the test but rather waits for the test to complete before failing.

  • @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.

    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)
    @Test
    public void testProcessRepeatedly() {
        // ...
    }

10.3.5 Spring TestContext Framework

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, whether JUnit or TestNG. The TestContext framework also places a great deal of importance on convention over configuration with reasonable defaults that can be overridden through annotation-based configuration.

In addition to generic testing infrastructure, the TestContext framework provides explicit support for JUnit and TestNG in the form of abstract support classes. For JUnit, Spring also provides a custom JUnit Runner that allows one to write so called POJO test classes. POJO test classes 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 or custom loaders, feel free to go directly to the configuration (context management, dependency injection, transaction management), support classes, and annotation support sections.

10.3.5.1 Key abstractions

The core of the framework consists of the TestContext and TestContextManager classes and the TestExecutionListener, ContextLoader, and SmartContextLoader interfaces. A TestContextManager is created on a per-test basis (e.g., for the execution of a single test method in JUnit). The TestContextManager in turn manages a TestContext that holds the context of the current test. The TestContextManager also updates the state of the TestContext as the test progresses and delegates to TestExecutionListeners, which instrument the actual test execution by providing dependency injection, managing transactions, and so on. A ContextLoader (or SmartContextLoader) is responsible for loading an ApplicationContext for a given test class. Consult the Javadoc and the Spring test suite for further information and examples of various implementations.

  • TestContext: Encapsulates the context in which a test is executed, agnostic of the actual testing framework in use, and provides context management and caching support for the test instance for which it is responsible. The TestContext also delegates to a ContextLoader (or SmartContextLoader) to load an ApplicationContext if requested.

  • TestContextManager: The main entry point into the Spring TestContext Framework, which manages a single TestContext and signals events to all registered TestExecutionListeners at well-defined test execution points:

    • prior to any before class methods of a particular testing framework

    • test instance preparation

    • prior to any before methods of a particular testing framework

    • after any after methods of a particular testing framework

    • after any after class 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 that are configured by default: DependencyInjectionTestExecutionListener, DirtiesContextTestExecutionListener, and TransactionalTestExecutionListener. Respectively, they support dependency injection of the test instance, handling of the @DirtiesContext annotation, and transactional test execution with default rollback semantics.

  • ContextLoader: Strategy interface introduced in Spring 2.5 for loading an ApplicationContext for an integration test managed by the Spring TestContext Framework.

    As of Spring 3.1, implement SmartContextLoader instead of this interface in order to provide support for configuration classes and active bean definition profiles.

  • SmartContextLoader: Extension of the ContextLoader interface introduced in Spring 3.1.

    The SmartContextLoader SPI supersedes the ContextLoader SPI that was introduced in Spring 2.5. Specifically, a SmartContextLoader can choose to process either resource locations or configuration classes. Furthermore, a SmartContextLoader can set active bean definition profiles in the context that it loads.

    Spring provides the following out-of-the-box implementations:

    • DelegatingSmartContextLoader: the default loader which delegates internally to an AnnotationConfigContextLoader or a GenericXmlContextLoader depending either on the configuration declared for the test class or on the presence of default locations or default configuration classes.

    • AnnotationConfigContextLoader: loads an application context from @Configuration classes.

    • GenericXmlContextLoader: loads an application context from XML resource locations.

    • GenericPropertiesContextLoader: loads an application context from Java Properties files.

The following sections explain how to configure the TestContext framework through annotations and provide working examples of how to write unit and integration tests with the framework.

10.3.5.2 Context management

Each TestContext provides context management and caching support for the test instance it is responsible for. 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 is supplied to the test instance. Note that AbstractJUnit4SpringContextTests and AbstractTestNGSpringContextTests implement ApplicationContextAware and therefore provide access to the ApplicationContext out-of-the-box.

[Tip]@Autowired ApplicationContext

As an alternative to implementing the ApplicationContextAware interface, you can inject the application context for your test class through the @Autowired annotation on either a field or setter method. For example:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {

    @Autowired
    private ApplicationContext applicationContext;

    // class body...
}

Dependency injection via @Autowired is provided by the DependencyInjectionTestExecutionListener which is configured by default (see Section 10.3.5.3, “Dependency injection of test fixtures”).

Test classes that use the TestContext framework do not need to extend any particular class or implement a specific interface to configure their application context. Instead, configuration is achieved simply by declaring the @ContextConfiguration annotation at the class level. If your test class does not explicitly declare application context resource locations or configuration classes, the configured ContextLoader determines how to load a context from a default location or default configuration classes.

The following sections explain how to configure an ApplicationContext via XML configuration files or @Configuration classes using Spring's @ContextConfiguration annotation.

Context configuration with XML resources

To load an ApplicationContext for your tests using XML configuration files, annotate your test class with @ContextConfiguration and configure the locations attribute with an array that contains the resource locations of XML configuration metadata. A plain path — for example "context.xml" — will be treated as a classpath resource that is relative to the package in which the test class is defined. A path starting with a slash is treated as an absolute classpath location, for example "/org/example/config.xml". A path which represents a resource URL (i.e., a path prefixed with classpath:, file:, http:, etc.) will be used as is. Alternatively, you can implement and configure your own custom ContextLoader or SmartContextLoader for advanced use cases.

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/app-config.xml" and
// "/test-config.xml" in the root of the classpath
@ContextConfiguration(locations={"/app-config.xml", "/test-config.xml"})
public class MyTest {
    // class body...
}

@ContextConfiguration supports an alias for the locations attribute through the standard Java value attribute. Thus, if you do not need to configure a custom ContextLoader, you can omit the declaration of the locations attribute name and declare the resource locations by using the shorthand format demonstrated in the following example.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/app-config.xml", "/test-config.xml"})
public class MyTest {
    // class body...
}

If you omit both the locations and value attributes from the @ContextConfiguration annotation, the TestContext framework will attempt to detect a default XML resource location. Specifically, GenericXmlContextLoader detects a default location based on the name of the test class. If your class is named com.example.MyTest, GenericXmlContextLoader loads 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...
}
Context configuration with @Configuration classes

To load an ApplicationContext for your tests using @Configuration classes (see Section 4.12, “Java-based container configuration”), annotate your test class with @ContextConfiguration and configure the classes attribute with an array that contains references to configuration classes. Alternatively, you can implement and configure your own custom ContextLoader or SmartContextLoader for advanced use cases.

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes={AppConfig.class, TestConfig.class})
public class MyTest {
    // class body...
}

If you omit the classes attribute from the @ContextConfiguration annotation, the TestContext framework will attempt to detect the presence of default configuration classes. Specifically, AnnotationConfigContextLoader will detect all static inner classes of the annotated test class that meet the requirements for configuration class implementations as specified in the Javadoc for @Configuration. In the following example, the OrderServiceTest class declares a static inner configuration class named Config that will be automatically used to load the ApplicationContext for the test class. Note that the name of the configuration class is arbitrary. In addition, a test class can contain more than one static inner configuration class if desired.

package com.example;
 
@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from the static inner Config class
@ContextConfiguration
public class OrderServiceTest {
 
    @Configuration
    static class Config {
 
        // this bean will be injected into the OrderServiceTest class
        @Bean
        public OrderService orderService() {
            OrderService orderService = new OrderServiceImpl();
            // set properties, etc.
            return orderService;
        }
    }
 
    @Autowired
    private OrderService orderService;
 
    @Test
    public void testOrderService() {
        // test the orderService
    }

}
Mixing XML resources and @Configuration classes

It may sometimes be desirable to mix XML resources and @Configuration classes to configure an ApplicationContext for your tests. For example, if you use XML configuration in production, you may decide that you want to use @Configuration classes to configure specific Spring-managed components for your tests, or vice versa. As mentioned in Section 10.3.4.1, “Spring Testing Annotations” the TestContext framework does not allow you to declare both via @ContextConfiguration, but this does not mean that you cannot use both.

If you want to use XML and @Configuration classes to configure your tests, you will have to pick one as the entry point, and that one will have to include or import the other. For example, in XML you can include @Configuration classes via component scanning or define them as normal Spring beans in XML; whereas, in a @Configuration class you can use @ImportResource to import XML configuration files. Note that this behavior is semantically equivalent to how you configure your application in production: in production configuration you will define either a set of XML resource locations or a set of @Configuration classes that your production ApplicationContext will be loaded from, but you still have the freedom to include or import the other type of configuration.

Context configuration inheritance

@ContextConfiguration supports a boolean inheritLocations attribute that denotes whether resource locations or configuration classes declared by superclasses should be inherited. The default value is true. This means that an annotated class inherits the resource locations or configuration classes declared by any annotated superclasses. Specifically, the resource locations or configuration classes for an annotated test class are appended to the list of resource locations or configuration classes declared by annotated superclasses. Thus, subclasses have the option of extending the list of resource locations or configuration classes.

If @ContextConfiguration's inheritLocations attribute is set to false, the resource locations or configuration classes for the annotated class shadow and effectively replace any resource locations or configuration classes defined by superclasses.

In the following example that uses XML resource locations, the ApplicationContext for ExtendedTest will be loaded from "base-config.xml" and "extended-config.xml", in that order. Beans defined in "extended-config.xml" may therefore override (i.e., replace) those defined in "base-config.xml".

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/base-config.xml" in the root of the classpath
@ContextConfiguration("/base-config.xml")
public class BaseTest {
    // class body...
}

// ApplicationContext will be loaded from "/base-config.xml" and "/extended-config.xml"
// in the root of the classpath
@ContextConfiguration("/extended-config.xml")
public class ExtendedTest extends BaseTest {
    // class body...
}

Similarly, in the following example that uses configuration classes, the ApplicationContext for ExtendedTest will be loaded from the BaseConfig and ExtendedConfig configuration classes, in that order. Beans defined in ExtendedConfig may therefore override (i.e., replace) those defined in BaseConfig.

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from BaseConfig
@ContextConfiguration(classes=BaseConfig.class)
public class BaseTest {
    // class body...
}

// ApplicationContext will be loaded from BaseConfig and ExtendedConfig
@ContextConfiguration(classes=ExtendedConfig.class)
public class ExtendedTest extends BaseTest {
    // class body...
}
Context configuration with environment profiles

Spring 3.1 introduces first-class support in the framework for the notion of environments and profiles (a.k.a., bean definition profiles), and integration tests can now be configured to activate particular bean definition profiles for various testing scenarios. This is achieved by annotating a test class with the new @ActiveProfiles annotation and supplying a list of profiles that should be activated when loading the ApplicationContext for the test.

[Note]Note

@ActiveProfiles may be used with any implementation of the new SmartContextLoader SPI, but @ActiveProfiles is not supported with implementations of the older ContextLoader SPI.

Let's take a look at some examples with XML configuration and @Configuration classes.

<!-- app-config.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="...">

    <bean id="transferService"
        class="com.bank.service.internal.DefaultTransferService">
        <constructor-arg ref="accountRepository"/>
        <constructor-arg ref="feePolicy"/>
    </bean>

    <bean id="accountRepository"
        class="com.bank.repository.internal.JdbcAccountRepository">
        <constructor-arg ref="dataSource"/>
    </bean>

    <bean id="feePolicy"
        class="com.bank.service.internal.ZeroFeePolicy"/>

    <beans profile="dev">
        <jdbc:embedded-database id="dataSource">
            <jdbc:script
                location="classpath:com/bank/config/sql/schema.sql"/>
            <jdbc:script
                location="classpath:com/bank/config/sql/test-data.sql"/>
        </jdbc:embedded-database>
    </beans>

    <beans profile="production">
        <jee:jndi-lookup id="dataSource"
            jndi-name="java:comp/env/jdbc/datasource"/>
    </beans>

</beans>
package com.bank.service;

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "classpath:/app-config.xml"
@ContextConfiguration("/app-config.xml")
@ActiveProfiles("dev")
public class TransferServiceTest {

   @Autowired
   private TransferService transferService;

   @Test
   public void testTransferService() {
       // test the transferService
   }
}

When TransferServiceTest is run, its ApplicationContext will be loaded from the app-config.xml configuration file in the root of the classpath. If you inspect app-config.xml you'll notice that the accountRepository bean has a dependency on a dataSource bean; however, dataSource is not defined as a top-level bean. Instead, dataSource is defined twice: once in the production profile and once in the dev profile.

By annotating TransferServiceTest with @ActiveProfiles("dev") we instruct the Spring TestContext Framework to load the ApplicationContext with the active profiles set to {"dev"}. As a result, an embedded database will be created, and the accountRepository bean will be wired with a reference to the development DataSource. And that's likely what we want in an integration test.

The following code listings demonstrate how to implement the same configuration and integration test but using @Configuration classes instead of XML.

@Configuration
@Profile("dev")
public class StandaloneDataConfig {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript("classpath:com/bank/config/sql/schema.sql")
            .addScript("classpath:com/bank/config/sql/test-data.sql")
            .build();
    }
}
@Configuration
@Profile("production")
public class JndiDataConfig {

    @Bean
    public DataSource dataSource() throws Exception {
        Context ctx = new InitialContext();
        return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
    }
}
@Configuration
public class TransferServiceConfig {

    @Autowired DataSource dataSource;

    @Bean
    public TransferService transferService() {
        return new DefaultTransferService(accountRepository(),
            feePolicy());
    }

    @Bean
    public AccountRepository accountRepository() {
        return new JdbcAccountRepository(dataSource);
    }

    @Bean
    public FeePolicy feePolicy() {
        return new ZeroFeePolicy();
    }

}
package com.bank.service;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
   classes={
       TransferServiceConfig.class,
       StandaloneDataConfig.class,
       JndiDataConfig.class})
@ActiveProfiles("dev")
public class TransferServiceTest {

   @Autowired
   private TransferService transferService;

   @Test
   public void testTransferService() {
       // test the transferService
   }
}

In this variation, we have split the XML configuration into three independent @Configuration classes:

  • TransferServiceConfig: acquires a dataSource via dependency injection using @Autowired

  • StandaloneDataConfig: defines a dataSource for an embedded database suitable for developer tests

  • JndiDataConfig: defines a dataSource that is retrieved from JNDI in a production environment

As with the XML-based configuration example, we still annotate TransferServiceTest with @ActiveProfiles("dev"), but this time we specify all three configuration classes via the @ContextConfiguration annotation. The body of the test class itself remains completely unchanged.

Context caching

Once the TestContext framework loads an ApplicationContext for a test, that context will be cached and reused for all subsequent tests that declare the same unique context configuration within the same test suite. To understand how caching works, it is important to understand what is meant by unique and test suite.

An ApplicationContext can be uniquely identified by the combination of configuration parameters that are used to load it. Consequently, the unique combination of configuration parameters are used to generate a key under which the context is cached. The TestContext framework uses the following configuration parameters to build the context cache key:

  • locations (from @ContextConfiguration)

  • classes (from @ContextConfiguration)

  • contextLoader (from @ContextConfiguration)

  • activeProfiles (from @ActiveProfiles)

For example, if TestClassA specifies {"app-config.xml", "test-config.xml"} for the locations (or value) attribute of @ContextConfiguration, the TestContext framework will load the corresponding ApplicationContext and store it in a static context cache under a key that is based solely on those locations. So if TestClassB also defines {"app-config.xml", "test-config.xml"} for its locations (either explicitly or implicitly through inheritance) and does not define a different ContextLoader or different active profiles, then the same ApplicationContext will be shared by both test classes. This means that the setup cost for loading an application context is incurred only once (per test suite), and subsequent test execution is much faster.

[Note]Test suites and forked processes

The Spring TestContext framework stores application contexts in a static cache. This means that the context is literally stored in a static variable. In other words, if tests execute in separate processes the static cache will be cleared between each test execution, and this will effectively disable the caching mechanism.

To benefit from the caching mechanism, all tests must run within the same process or test suite. This can be achieved by executing all tests as a group within an IDE. Similarly, when executing tests with a build framework such as Ant or Maven it is important to make sure that the build framework does not fork between tests. For example, if the forkMode for the Maven Surefire plug-in is set to always or pertest, the TestContext framework will not be able to cache application contexts between test classes and the build process will run significantly slower as a result.

In the unlikely case that a test corrupts the application context and requires reloading — for example, by modifying a bean definition or the state of an application object — you can annotate your test class or test method with @DirtiesContext (see the discussion of @DirtiesContext in Section 10.3.4.1, “Spring Testing Annotations”). This instructs Spring to remove the context from the cache and rebuild the application context before executing the next test. Note that support for the @DirtiesContext annotation is provided by the DirtiesContextTestExecutionListener which is enabled by default.

10.3.5.3 Dependency injection of test fixtures

When you use the DependencyInjectionTestExecutionListener — which is configured by default — the dependencies of your test instances are injected from beans in the application context that you configured with @ContextConfiguration. You may use 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 the annotation support introduced in Spring 2.5 and 3.0, you can use Spring's @Autowired annotation or the @Inject annotation from JSR 300.

[Tip]Tip

The TestContext framework does not instrument the manner in which a test instance is instantiated. Thus the use of @Autowired or @Inject for constructors has no effect for test classes.

Because @Autowired is used to perform 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 @Autowired in conjunction with @Qualifier. As of Spring 3.0 you may also choose to use @Inject in conjunction with @Named. Alternatively, if your test class has access to its ApplicationContext, you can perform an explicit lookup by using (for example) a call to applicationContext.getBean("titleRepository").

If you do not want dependency injection applied to your test instances, simply do not annotate fields or setter methods with @Autowired or @Inject. 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 of testing a HibernateTitleRepository class, as outlined in the Goals section. The next two code listings demonstrate the use of @Autowired on fields and setter methods. The application context configuration is presented after all sample code listings.

[Note]Note

The dependency injection behavior in the following code listings is not specific to JUnit. The same DI techniques can be used in conjunction with any testing framework.

The following examples make calls to static assertion methods such as assertNotNull() but without prepending the call with Assert. In such cases, assume that the method was properly imported through an import static declaration that is not shown in the example.

The first code listing shows a JUnit-based implementation of the test class that uses @Autowired for field injection.

@RunWith(SpringJUnit4ClassRunner.class)
// specifies the Spring configuration to load for this test fixture
@ContextConfiguration("repository-config.xml")
public class HibernateTitleRepositoryTests {

    // this instance will be dependency injected by type
    @Autowired    
    private HibernateTitleRepository titleRepository;

    @Test
    public void findById() {
        Title title = titleRepository.findById(new Long(10));
        assertNotNull(title);
    }
}

Alternatively, you can configure the class to use @Autowired for setter injection as seen below.

@RunWith(SpringJUnit4ClassRunner.class)
// specifies the Spring configuration to load for this test fixture
@ContextConfiguration("repository-config.xml")
public class HibernateTitleRepositoryTests {

    // this instance will be dependency injected by type
    private HibernateTitleRepository titleRepository;

    @Autowired
    public void setTitleRepository(HibernateTitleRepository titleRepository) {
        this.titleRepository = titleRepository;
    }

    @Test
    public void findById() {
        Title title = titleRepository.findById(new Long(10));
        assertNotNull(title);
    }
}

The preceding code listings use the same XML context file referenced by the @ContextConfiguration annotation (that is, repository-config.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-3.0.xsd">

    <!-- this bean will be injected into the HibernateTitleRepositoryTests class -->
    <bean id="titleRepository" class="com.foo.repository.hibernate.HibernateTitleRepository">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    
    <bean id="sessionFactory"
            class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <!-- configuration elided for brevity -->
    </bean>

</beans>
[Note]Note

If you are extending from a Spring-provided test base class that happens to use @Autowired on one of its setter methods, you might have multiple beans of the affected type defined in your application context: for example, multiple DataSource beans. In such a case, you can override the setter method and use the @Qualifier annotation to indicate a specific target bean as follows, but make sure to delegate to the overridden method in the superclass as well.

// ...

    @Autowired
    @Override
    public void setDataSource(@Qualifier("myDataSource") DataSource dataSource) {
        super.setDataSource(dataSource);
    }

// ...

The specified qualifier value indicates the specific DataSource bean to inject, narrowing the set of type matches to a specific bean. Its value is matched against <qualifier> declarations within the corresponding <bean> definitions. The bean name is used as a fallback qualifier value, so you may effectively also point to a specific bean by name there (as shown above, assuming that "myDataSource" is the bean id).

10.3.5.4 Transaction management

In the TestContext framework, transactions are managed by the TransactionalTestExecutionListener. Note that TransactionalTestExecutionListener is configured 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 by @ContextConfiguration semantics. In addition, you must declare @Transactional either at the class or method level for your tests.

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 annotation support section.

If transactions are not enabled for the entire test class, you can annotate methods explicitly with @Transactional. To control whether a transaction should commit for a particular test method, you can use the @Rollback annotation to override the class-level default rollback setting.

AbstractTransactionalJUnit4SpringContextTests and AbstractTransactionalTestNGSpringContextTests are preconfigured for transactional support at the class level.

Occasionally 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 (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 ensures that your before transaction method or after transaction method is executed at the appropriate time.

[Tip]Tip

Any before methods (such as methods annotated with JUnit's @Before) and any after methods (such as methods annotated with JUnit's @After) are executed within a transaction. In addition, methods annotated with @BeforeTransaction or @AfterTransaction are naturally not executed for tests annotated with @NotTransactional. However, @NotTransactional is deprecated as of Spring 3.0.

The following JUnit-based example displays a fictitious integration testing scenario highlighting several transaction-related annotations. Consult the annotation support section 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
    }

}
[Note]Avoid false positives when testing ORM code

When you test application code that manipulates the state of the Hibernate session, make sure to flush the underlying session within test methods that execute that code. Failing to flush the underlying session can produce false positives: your test may pass, but the same code throws an exception in a live, production environment. In the following Hibernate-based example test case, one method demonstrates a false positive, and the other method correctly exposes the results of flushing the session. Note that this applies to JPA and any other ORM frameworks that maintain an in-memory unit of work.

// ...

@Autowired
private SessionFactory sessionFactory;

@Test // no expected exception!
public void falsePositive() {
    updateEntityInHibernateSession();
    // False positive: an exception will be thrown once the session is
    // finally flushed (i.e., in production code)
}

@Test(expected = GenericJDBCException.class)
public void updateWithSessionFlush() {
    updateEntityInHibernateSession();
    // Manual flush is required to avoid false positive in test
    sessionFactory.getCurrentSession().flush();
}

// ...

10.3.5.5 TestContext support classes

JUnit support classes

The org.springframework.test.context.junit4 package provides support classes for JUnit 4.5+ based test cases.

  • AbstractJUnit4SpringContextTests: Abstract base test class that integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a JUnit 4.5+ environment.

    When you extend AbstractJUnit4SpringContextTests, you can access the following protected instance variable:

    • applicationContext: Use this variable 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 can access the following protected instance variables:

    • applicationContext: Inherited from the AbstractJUnit4SpringContextTests superclass. Use this variable to perform explicit bean lookups or to test the state of the context as a whole.

    • simpleJdbcTemplate: Use this variable to execute SQL statements to query the database. Such queries can be used to confirm database state both prior to and after execution of database-related application code, and Spring ensures that such queries run in the scope of the same transaction as the application code. When used in conjunction with an ORM tool, be sure to avoid false positives.

[Tip]Tip

These classes are a convenience for extension. If you do not want your test classes to be tied to a Spring-specific class hierarchy — for example, if you want to directly extend the class you are testing — you can configure your own custom test classes by using @RunWith(SpringJUnit4ClassRunner.class), @ContextConfiguration, @TestExecutionListeners, and so on.

Spring JUnit Runner

The Spring TestContext Framework offers full integration with JUnit 4.5+ through a custom runner (tested on JUnit 4.5 – 4.9). By annotating test classes with @RunWith(SpringJUnit4ClassRunner.class), developers can implement standard JUnit-based 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, and so on. The following code listing displays the minimal requirements for configuring a test class to run with the custom Spring Runner. @TestExecutionListeners is configured with an empty list in order to disable the default listeners, which otherwise would require an ApplicationContext to be configured through @ContextConfiguration.

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({})
public class SimpleTest {

    @Test
    public void testMethod() {
        // execute test logic...
    }
}
TestNG support classes

The org.springframework.test.context.testng package provides support classes for TestNG based test cases.

  • AbstractTestNGSpringContextTests: Abstract base test class that integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a TestNG environment.

    When you extend AbstractTestNGSpringContextTests, you can access the following protected instance variable:

    • applicationContext: Use this variable 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 can access the following protected instance variables:

    • applicationContext: Inherited from the AbstractTestNGSpringContextTests superclass. Use this variable to perform explicit bean lookups or to test the state of the context as a whole.

    • simpleJdbcTemplate: Use this variable to execute SQL statements to query the database. Such queries can be used to confirm database state both prior to and after execution of database-related application code, and Spring ensures that such queries run in the scope of the same transaction as the application code. When used in conjunction with an ORM tool, be sure to avoid false positives.

[Tip]Tip

These classes are a convenience for extension. If you do not want your test classes to be tied to a Spring-specific class hierarchy — for example, if you want to directly extend the class you are testing — you can configure your own custom test classes by using @ContextConfiguration, @TestExecutionListeners, and so on, 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.

10.3.6 PetClinic Example

The PetClinic application, available from the samples repository, illustrates several features of the Spring TestContext Framework in a JUnit 4.5+ environment. Most test functionality is included in the AbstractClinicTests, for which a partial listing is shown below:

import static org.junit.Assert.assertEquals;
// import ...

@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 (through the DependencyInjectionTestExecutionListener) and transactional behavior (through the TransactionalTestExecutionListener).

  • The clinic instance variable — the application object being tested — is set by Dependency Injection through @Autowired semantics.

  • The testGetVets() method illustrates how you can use the inherited countRowsInTable() method to easily verify the number of rows in a given table, thus verifying 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 that use a database, most of the tests in AbstractClinicTests depend on a minimum amount of data already in the database before the test cases run. Alternatively, you might choose to populate the database within the test fixture set up of your test cases — again, within the same transaction as the tests.

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 that must declare a PlatformTransactionManager and a concrete implementation of Clinic.

For example, the Hibernate implementation of the PetClinic tests contains the following implementation. 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. Because @ContextConfiguration is declared without any specific resource locations, the Spring TestContext Framework loads 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 { }

In a large-scale application, the Spring configuration is often split across multiple files. Consequently, configuration locations are typically 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 SessionFactory 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 or <jee:jndi-lookup> 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 a '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.

10.4 Further Resources

Consult the following resources for more information about testing:

  • JUnit: “A programmer-oriented testing framework for Java”. Used by the Spring Framework in its test suite.

  • TestNG: A testing framework inspired by JUnit with added support for Java 5 annotations, test groups, data-driven testing, distributed testing, etc.

  • MockObjects.com: Web site dedicated to mock objects, a technique for improving the design of code within test-driven development.

  • "Mock Objects": Article in Wikipedia.

  • EasyMock: Java library “that provides Mock Objects for interfaces (and objects through the class extension) by generating them on the fly using Java's proxy mechanism.” Used by the Spring Framework in its test suite.

  • JMock: Library that supports test-driven development of Java code with mock objects.

  • Mockito: Java mock library based on the test spy pattern.

  • DbUnit: JUnit extension (also usable with Ant and Maven) targeted for database-driven projects that, among other things, puts your database into a known state between test runs.

  • Grinder: Java load testing framework.