diff --git a/spring-framework-reference/src/testing.xml b/spring-framework-reference/src/testing.xml
index 450c1eb5ee1..6fe33be52b2 100644
--- a/spring-framework-reference/src/testing.xml
+++ b/spring-framework-reference/src/testing.xml
@@ -115,9 +115,9 @@
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.
+ in combination with JUnit, TestNG, or any other testing framework for
+ unit tests dealing with Spring MVC ModelAndView
+ objects.
Unit testing Spring MVC Controllers
@@ -157,22 +157,19 @@
- 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 got it from (see
- the section on Dependency
- Management for an explanation). This library includes
- the org.springframework.test package, which
+ 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.
+ 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
JUnit 3.8 support is deprecated
- As of Spring 3.0, the legacy JUnit 3.8 base class hierarchy (i.e.,
+ 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.
+ 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)
- 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.
+ 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.Goals of integration testing
- Spring's integration testing support has the following
- primary goals:
+ Spring's integration testing support has the following primary
+ goals:
- To manage Spring IoC container
- caching between test execution.
+ To manage Spring IoC
+ container caching between test execution.
- To provide Dependency Injection of
- test fixture instances.
+ To provide Dependency
+ Injection of test fixture instances.
- To provide transaction management
- appropriate to integration testing.
+ To provide transaction
+ management appropriate to integration testing.
- To supply Spring-specific
- base classes that assist developers in writing integration
+ To supply Spring-specific base
+ classes that assist developers in writing integration
tests.
@@ -241,7 +244,7 @@
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
+ 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
@@ -249,8 +252,10 @@
every test fixture leads to slower overall test runs that could reduce
productivity.
+
+
Test classes provide an array containing the resource locations
- of XML configuration metadata — typically in the classpath — that is
+ of XML configuration metadata — typically in the classpath — that is
used to configure the application. These locations are the same as or
similar to the list of configuration locations specified in
web.xml or other deployment configuration
@@ -258,13 +263,13 @@
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 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.
+ test. Thus the setup cost is incurred only once (per test suite), and
+ subsequent test execution is much faster. 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
@@ -282,12 +287,13 @@
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.
+ 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 say, the Title domain object. We want
- to write integration tests that test all of the following
+ HibernateTitleRepository, that performs data
+ access logic for say, the Title domain object.
+ We want to write integration tests that test all of the following
areas:
@@ -305,9 +311,9 @@
- The logic of the HibernateTitleRepository:
- does the configured instance of this class perform as
- anticipated?
+ The logic of the
+ HibernateTitleRepository: does the
+ configured instance of this class perform as anticipated?
@@ -321,8 +327,8 @@
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.
+ 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
@@ -336,9 +342,9 @@
a PlatformTransactionManager bean defined in
the test's application context.
- If you want a transaction to commit — unusual, but occasionally
+ 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
+ database — the TestContext framework can be instructed to cause the
transaction to commit instead of roll back via the @TransactionConfiguration
and
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.
+ 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.
@@ -408,7 +414,7 @@
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,
+ framework. Refer to the respective Javadoc for further information,
including default attribute values, attribute aliases, and so on.
@@ -422,7 +428,10 @@
@ContextConfiguration defines the
application context resource locations to load as
well as the ContextLoader strategy to
- use for loading the context.
+ 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 CustomConfiguredApplicationContextTests {
@@ -433,7 +442,7 @@ public class CustomConfiguredApplicationContextTests {
@ContextConfiguration
supports inherited resource locations by
default. See Context
- management and caching and JavaDoc for an example and
+ management and caching and Javadoc for an example and
further details.
@@ -444,11 +453,11 @@ public class CustomConfiguredApplicationContextTests {
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,
+ 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:
+ @DirtiesContext is supported in the
+ following scenarios:
@@ -474,12 +483,13 @@ public class CustomConfiguredApplicationContextTests {
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.
+ 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 {
@@ -511,8 +521,8 @@ public void testProcessWhichDirtiesAppCtx() {
Defines class-level metadata for configuring which
TestExecutionListeners should be
registered with the TestContextManager.
- Typically, @TestExecutionListeners
- is used in conjunction with
+ Typically, @TestExecutionListeners is
+ used in conjunction with
@ContextConfiguration.@ContextConfiguration
@@ -523,7 +533,7 @@ public class CustomTestExecutionListenerTests {
@TestExecutionListeners
supports inherited listeners by default. See
- the JavaDoc for an example and further details.
+ the Javadoc for an example and further details.
@@ -534,8 +544,9 @@ public class CustomTestExecutionListenerTests {
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
+ 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
@@ -548,14 +559,14 @@ public class CustomConfiguredTransactionalTests {
}
- 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.
+ 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.
@@ -646,9 +657,8 @@ public void testProcessWithoutTransaction() {
The following annotations are only supported
when used in conjunction with the SpringJUnit4ClassRunner or
- the JUnit support
- classes.
+ the JUnit
+ support classes.
@@ -701,31 +711,6 @@ public class CustomProfileValueSourceTests {
}
-
- @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
-}
-
- Using Spring's
- @ExpectedException annotation in
- conjunction with JUnit's
- @Test(expected=...) configuration
- would lead to an unresolvable conflict. Developers must therefore
- choose one or the other when integrating with JUnit, in which case
- it is generally preferable to use the explicit JUnit configuration.
-
-
@Timed
@@ -844,19 +829,19 @@ public void testProcessRepeatedly() {
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.
+ 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.
+ 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
@@ -884,7 +869,7 @@ public void testProcessRepeatedly() {
test progresses and delegates to
TestExecutionListeners, which
instrument the actual test execution, by providing dependency
- injection, managing transactions, and so on. Consult the JavaDoc and
+ injection, managing transactions, and so on. Consult the Javadoc and
the Spring test suite for further information and examples of various
configurations.
@@ -892,7 +877,8 @@ public void testProcessRepeatedly() {
TestContext: Encapsulates the context
in which a test is executed, agnostic of the actual testing
- framework in use.
+ framework in use, and provides context management and caching
+ support for the test instance for which it is responsible.
@@ -902,26 +888,30 @@ public void testProcessRepeatedly() {
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
+ prior to any before methods of a
+ particular testing framework
+
- after any after 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
+ after any after class methods of a
+ particular testing framework
@@ -942,7 +932,8 @@ public void testProcessRepeatedly() {
Respectively, they support dependency injection of the test
instance, handling of the
@DirtiesContext annotation, and
- transactional test execution with default rollback semantics.
+ transactional test execution with default rollback
+ semantics.
@@ -990,20 +981,20 @@ public class MyTest {
}
- In contrast to the deprecated JUnit 3.8 legacy class
- hierarchy, test classes that use the TestContext framework do not need
- to override any protected instance methods to
+ In contrast to the deprecated JUnit 3.8 legacy class hierarchy,
+ test classes that 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
application context resource locations, the
configured ContextLoader determines how
- and whether to load a context from a default location. For
- example, GenericXmlContextLoader, which is the
- default ContextLoader, generates a
- default location based on the name of the test class. If your class is
- named com.example.MyTest,
+ and whether to load a context from a default location. For example,
+ GenericXmlContextLoader, which is the default
+ ContextLoader, generates 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".
@@ -1022,16 +1013,16 @@ public class MyTest {
@ContextConfiguration with an array
that contains the resource locations of XML configuration metadata
(assuming an XML-capable ContextLoader
- has been configured, which is the default). A plain path, for
- example "context.xml", will be treated as a
- classpath resource from the same package in which the test class
- is defined. A path starting with a slash is treated as a fully qualified
- classpath location, for example "/org/example/config.xml".
- A path which represents a URL (i.e., a path prefixed with
+ has been configured, which is the default). A plain path, for example
+ "context.xml", will be treated as a classpath
+ resource from the same package in which the test class is defined. A
+ path starting with a slash is treated as a fully qualified classpath
+ location, for example "/org/example/config.xml". A
+ path which represents a 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.
+ http:, etc.) will be used as
+ is. Alternatively, you can implement and configure your own
+ custom ContextLoader.
@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/applicationContext.xml" and "/applicationContext-test.xml"
@@ -1049,10 +1040,9 @@ public class MyTest {
attribute name and declare the resource locations by using the
shorthand format demonstrated in the following example.
-
- @ContextConfiguration also supports a
- boolean inheritLocations attribute that denotes
- whether resource locations from superclasses should be
+ @ContextConfiguration also
+ supports a boolean inheritLocations attribute that
+ denotes whether resource locations from superclasses should be
inherited. The default value is
true, which means that an annotated class inherits
the resource locations defined by an annotated superclass.
@@ -1060,7 +1050,8 @@ public class MyTest {
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
+ following example, the
+ ApplicationContext for
ExtendedTest is loaded from "/base-context.xml"
and "/extended-context.xml", in that
order. Beans defined in "/extended-context.xml" may therefore override
@@ -1082,38 +1073,38 @@ public class ExtendedTest extends BaseTest {
If inheritLocations is set to
false, the resource locations for the annotated
- class shadow and effectively replace any resource locations defined
- by a superclass.
+ class shadow and effectively replace any resource locations defined by
+ a superclass.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 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 (assuming
+ test. Thus the setup cost is incurred only once (per test suite), and
+ subsequent test execution is much faster. 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 (assuming
DirtiesContextTestExecutionListener has been
- configured, which is the default). This instructs Spring to reload
- the configuration and rebuild the application context before
- executing the next test.
+ configured, which is the default). This instructs Spring to reload the
+ configuration and rebuild the application context before executing the
+ next test.Dependency Injection of test fixturesWhen you use the
- DependencyInjectionTestExecutionListener —
- which is configured by default — the dependencies of your
- test instances are injected from beans in 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 3.0, you
- can use Spring's @Autowired annotation
- or the @Inject annotation from JSR
- 300.
+ @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 3.0, you can use Spring's
+ @Autowired annotation or the
+ @Inject annotation from JSR 300.
The TestContext framework does not instrument the manner in
@@ -1123,42 +1114,42 @@ public class ExtendedTest extends BaseTest {
effect for test classes.
- Because @Autowired used solely performs autowiring by
+ 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
+ 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").
+ 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
+ @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.
+ 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.
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.
+ 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
@@ -1168,9 +1159,9 @@ public class ExtendedTest extends BaseTest {
example.
- The first code listing shows a JUnit-based implementation
- of the test class that uses @Autowired
- for field injection.
+ 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
@@ -1190,8 +1181,8 @@ public class HibernateTitleRepositoryTests {
}Alternatively, you can configure the class to use
- @Autowired for setter injection as
- seen below.
+ @Autowired for setter injection as seen
+ below.
@RunWith(SpringJUnit4ClassRunner.class)
// specifies the Spring configuration to load for this test fixture
@@ -1214,12 +1205,10 @@ public class HibernateTitleRepositoryTests {
}
}
-
-
The preceding code listings use the same XML context file
referenced by the @ContextConfiguration
- annotation (that is, repository-config.xml), which looks like
- this:
+ 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"
@@ -1248,7 +1237,7 @@ public class HibernateTitleRepositoryTests {
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
+ specific target bean as follows, but make sure to delegate to the
overridden method in the superclass as well.
// ...
@@ -1269,8 +1258,6 @@ public class HibernateTitleRepositoryTests {
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).
-
-
@@ -1314,8 +1301,8 @@ public class HibernateTitleRepositoryTests {
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).
+ test execution (if the test was configured not to roll back the
+ transaction).
TransactionalTestExecutionListener supports the
@BeforeTransaction and
@AfterTransaction annotations exactly
@@ -1328,11 +1315,11 @@ public class HibernateTitleRepositoryTests {
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
+ 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
@@ -1382,21 +1369,22 @@ public class FictitiousTransactionalTest {
}
-
+
+
Avoid false positives when testing ORM codeWhen 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.
+ 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.
// ...
@@ -1446,10 +1434,9 @@ public void updateWithSessionFlush() {
- applicationContext:
- Use this variable to perform explicit bean
- lookups or to test the state of the context as a
- whole.
+ applicationContext: Use this
+ variable to perform explicit bean lookups or to test the
+ state of the context as a whole.
@@ -1477,15 +1464,16 @@ public void updateWithSessionFlush() {
- simpleJdbcTemplate: Use this variable
- to execute SQL statements to query the database.
+ 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.
+ transaction as the application code. When used in
+ conjunction with an ORM tool, be sure to avoid false
+ positives.
@@ -1494,8 +1482,8 @@ public void updateWithSessionFlush() {
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
+ 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,
@@ -1509,17 +1497,18 @@ public void updateWithSessionFlush() {
The Spring TestContext Framework offers
full integration with JUnit 4.5+ through a custom runner (tested on
- JUnit 4.5 – 4.8.1). By annotating test classes with
+ JUnit 4.5 – 4.8.2). 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
+ 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)
@@ -1554,10 +1543,9 @@ public class SimpleTest {
- applicationContext:
- Use this variable to perform explicit bean
- lookups or to test the state of the context as a
- whole.
+ applicationContext: Use this
+ variable to perform explicit bean lookups or to test the
+ state of the context as a whole.
@@ -1585,15 +1573,16 @@ public class SimpleTest {
- simpleJdbcTemplate: Use this variable
- to execute SQL statements to query the database.
+ 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.
+ transaction as the application code. When used in
+ conjunction with an ORM tool, be sure to avoid false
+ positives.
@@ -1602,9 +1591,9 @@ public class SimpleTest {
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,
+ 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
@@ -1618,10 +1607,10 @@ public class SimpleTest {
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
+ 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:
@@ -1664,8 +1653,8 @@ public abstract class AbstractClinicTests extends Abstract
- The clinic instance variable — the
- application object being tested — is set by Dependency Injection
+ The clinic instance variable — the
+ application object being tested — is set by Dependency Injection
through @Autowired semantics.
@@ -1683,9 +1672,9 @@ public abstract class AbstractClinicTests extends Abstract
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.
+ 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.
@@ -1710,8 +1699,8 @@ public abstract class AbstractClinicTests extends Abstract
@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
+ defined in AbstractClinicTests-context.xml (i.e., the
+ inherited locations) and
HibernateClinicTests-context.xml, with
HibernateClinicTests-context.xml possibly overriding
beans defined in
@@ -1721,11 +1710,11 @@ public abstract class AbstractClinicTests extends Abstract
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
+ 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
+ variables — populated by Dependency Injection, naturally — such as a
SessionFactory in the case of an application
using Hibernate.
@@ -1761,15 +1750,15 @@ public class HibernateClinicTests extends AbstractClinicTests { }
JUnit:
- A programmer-oriented testing framework for Java.
- Used by the Spring Framework in its test suite.
+ 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.
+ framework inspired by JUnit with added support for Java 5 annotations,
+ test groups, data-driven testing, distributed testing, etc.
@@ -1785,11 +1774,11 @@ public class HibernateClinicTests extends AbstractClinicTests { }
- 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.
+ 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.