testing.adoc 163.9 KB
Newer Older
B
Brian Clozel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
[[testing]]
= Testing

[partintro]
--
The adoption of the test-driven-development (TDD) approach to software
development is certainly advocated by the Spring team, and so coverage of Spring's
support for integration testing is covered (alongside best practices for unit testing).
The Spring team has found that the correct use of IoC certainly does make both unit and
integration testing easier (in that the presence of setter methods and appropriate
constructors on classes makes them easier to wire together in a test without having to
set up service locator registries and suchlike)... the chapter dedicated solely to
testing will hopefully convince you of this as well.
--


[[testing-introduction]]
== 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,unit testing>> and on the benefits
of the Spring Framework's support for <<integration-testing,integration testing>>. __(A
thorough treatment of testing in the enterprise is beyond the scope of this reference
manual.)__




[[unit-testing]]
== 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,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.



[[mock-objects]]
=== Mock Objects


[[mock-objects-env]]
==== Environment
The `org.springframework.mock.env` package contains mock implementations of the
`Environment` and `PropertySource` abstractions (see <<beans-definition-profiles>>
and <<beans-property-source-abstraction>>). `MockEnvironment` and
`MockPropertySource` are useful for developing __out-of-container__ tests for code that
depends on environment-specific properties.


[[mock-objects-jndi]]
==== 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 ++DataSource++s 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.


[[mock-objects-servlet]]
==== 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 http://www.easymock.org[EasyMock] or existing
Servlet API mock objects such as http://www.mockobjects.com[MockObjects].


[[mock-objects-portlet]]
==== 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.



[[unit-testing-support-classes]]
=== Unit Testing support Classes


[[unit-testing-utilities]]
==== 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.


[[unit-testing-spring-mvc]]
==== 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.

.Unit testing Spring MVC Controllers
[TIP]
S
Stephane Nicoll 已提交
114
====
B
Brian Clozel 已提交
115 116 117 118 119 120
To test your Spring MVC ++Controller++s, use `ModelAndViewAssert` combined with
`MockHttpServletRequest`, `MockHttpSession`, and so on from the <<mock-objects-servlet,
`org.springframework.mock.web`>> package.

Note: As of Spring 4.0, the set of mocks in the `org.springframework.mock.web` package
is now based on the Servlet 3.0 API.
S
Stephane Nicoll 已提交
121
====
B
Brian Clozel 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388




[[integration-testing]]
== Integration Testing



[[integration-testing-overview]]
=== 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 <<dependency-management,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 Selenium 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 <<testcontext-framework,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.



[[integration-testing-goals]]
=== Goals of Integration Testing
Spring's integration testing support has the following primary goals:

* To manage <<testing-ctx-management,Spring IoC container caching>> between test
  execution.
* To provide <<testing-fixture-di,Dependency Injection of test fixture instances>>.
* To provide <<testing-tx,transaction management>> appropriate to integration testing.
* To supply <<testing-support-classes,Spring-specific base classes>> that assist
  developers in writing integration tests.

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


[[testing-ctx-management]]
==== Context management and caching
The Spring TestContext Framework provides consistent loading of Spring
++ApplicationContext++s and ++WebApplicationContext++s as well as 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 reduce developer productivity.

Test classes typically declare either an array of __resource locations__ for XML
configuration metadata -- often in the classpath -- or an array of __annotated 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, Maven, or Gradle 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 <<testcontext-ctx-management>> and <<testcontext-ctx-management-caching>> with the
TestContext framework.


[[testing-fixture-di]]
==== 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, ++DataSource++s, etc.), thus avoiding the need to duplicate
complex test fixture setup for individual test cases.

As an example, consider the scenario where we have a class, `HibernateTitleRepository`,
that implements 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-fixture-di,TestContext
framework>>.


[[testing-tx]]
==== Transaction management
One common issue in tests that access a real database is their effect 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 a test method deletes the contents of selected tables while running within
the transaction managed for the test, 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 a test 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
<<integration-testing-annotations, `@TransactionConfiguration`>> and
<<integration-testing-annotations, `@Rollback`>> annotations.

See transaction management with the <<testcontext-tx,TestContext framework>>.


[[testing-support-classes]]
==== 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 `JdbcTemplate`, 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 <<testcontext-tx-false-positives,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-support-classes,TestContext framework>>.



[[integration-testing-support-jdbc]]
=== JDBC Testing Support
The `org.springframework.test.jdbc` package contains `JdbcTestUtils`, which is a
collection of JDBC related utility functions intended to simplify standard database
testing scenarios. Specifically, `JdbcTestUtils` provides the following static utility
methods.

* `countRowsInTable(..)`: counts the number of rows in the given table
* `countRowsInTableWhere(..)`: counts the number of rows in the given table, using
the provided `WHERE` clause
* `deleteFromTables(..)`: deletes all rows from the specified tables
* `deleteFromTableWhere(..)`: deletes rows from the given table, using the provided
`WHERE` clause
* `dropTables(..)`: drops the specified tables

__Note that <<testcontext-support-classes-junit4,
`AbstractTransactionalJUnit4SpringContextTests`>> and
<<testcontext-support-classes-testng, `AbstractTransactionalTestNGSpringContextTests`>>
provide convenience methods which delegate to the aforementioned methods in
`JdbcTestUtils`.__

The `spring-jdbc` module provides support for configuring and launching an embedded
database which can be used in integration tests that interact with a database. For
details, see <<jdbc-embedded-database-support>> and
<<jdbc-embedded-database-dao-testing>>.



[[integration-testing-annotations]]
=== Annotations


[[integration-testing-annotations-spring]]
==== 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 corresponding javadocs 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 integration tests. Specifically, `@ContextConfiguration`
declares the application context resource `locations` or the annotated `classes`
that will be used to load the context.

+

Resource locations are typically XML configuration files located in the classpath;
whereas, annotated classes are typically `@Configuration` classes. However, resource
locations can also refer to files in the file system, and annotated classes can be
component classes, etc.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@ContextConfiguration**("/test-config.xml")
	public class XmlApplicationContextTests {
		// class body...
	}
----

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@ContextConfiguration**(**classes** = TestConfig.class)
	public class ConfigClassApplicationContextTests {
		// class body...
	}
----

+

As an alternative or in addition to declaring resource locations or annotated classes,
`@ContextConfiguration` may be used to declare `ApplicationContextInitializer` classes.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@ContextConfiguration**(**initializers** = CustomContextIntializer.class)
	public class ContextInitializerTests {
		// class body...
	}
----

+

`@ContextConfiguration` may optionally be used to declare the `ContextLoader` strategy
as well. Note, however, that you typically do not need to explicitly configure the
loader since the default loader supports either resource `locations` or annotated
`classes` as well as `initializers`.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@ContextConfiguration**(**locations** = "/test-context.xml", **loader** = CustomContextLoader.class)
	public class CustomLoaderXmlApplicationContextTests {
		// class body...
	}
----

+

[NOTE]
389
====
B
Brian Clozel 已提交
390 391 392
`@ContextConfiguration` provides support for __inheriting__ resource locations or
configuration classes as well as context initializers declared by superclasses by
default.
393
====
B
Brian Clozel 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532

+

See <<testcontext-ctx-management>> and the `@ContextConfiguration` javadocs for
further details.

* `@WebAppConfiguration`

+

A class-level annotation that is used to declare that the `ApplicationContext` loaded
for an integration test should be a `WebApplicationContext`. The mere presence of
`@WebAppConfiguration` on a test class ensures that a `WebApplicationContext` will be
loaded for the test, using the default value of `"file:src/main/webapp"` for the path to
the root of the web application (i.e., the __resource base path__). The resource base
path is used behind the scenes to create a `MockServletContext` which serves as the
`ServletContext` for the test's `WebApplicationContext`.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	**@WebAppConfiguration**
	public class WebAppTests {
		// class body...
	}
----

+

To override the default, specify a different base resource path via the __implicit__
`value` attribute. Both `classpath:` and `file:` resource prefixes are supported. If no
resource prefix is supplied the path is assumed to be a file system resource.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	**@WebAppConfiguration("classpath:test-web-resources")**
	public class WebAppTests {
		// class body...
	}
----

+

Note that `@WebAppConfiguration` must be used in conjunction with
`@ContextConfiguration`, either within a single test class or within a test class
hierarchy. See the `@WebAppConfiguration` javadocs for further details.

+

* `@ContextHierarchy`

+

A class-level annotation that is used to define a hierarchy of ++ApplicationContext++s
for integration tests. `@ContextHierarchy` should be declared with a list of one or more
`@ContextConfiguration` instances, each of which defines a level in the context
hierarchy. The following examples demonstrate the use of `@ContextHierarchy` within a
single test class; however, `@ContextHierarchy` can also be used within a test class
hierarchy.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextHierarchy({
		@ContextConfiguration("/parent-config.xml"),
		@ContextConfiguration("/child-config.xml")
	})
	public class ContextHierarchyTests {
		// class body...
	}
----

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@WebAppConfiguration
	@ContextHierarchy({
		@ContextConfiguration(classes = AppConfig.class),
		@ContextConfiguration(classes = WebConfig.class)
	})
	public class WebIntegrationTests {
		// class body...
	}
----

+

If you need to merge or override the configuration for a given level of the context
hierarchy within a test class hierarchy, you must explicitly name that level by
supplying the same value to the `name` attribute in `@ContextConfiguration` at each
corresponding level in the class hierarchy. See
<<testcontext-ctx-management-ctx-hierarchies>> and the `@ContextHierarchy` javadocs
for further examples.

* `@ActiveProfiles`

+

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

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	**@ActiveProfiles**("dev")
	public class DeveloperTests {
		// class body...
	}
----

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	**@ActiveProfiles**({"dev", "integration"})
	public class DeveloperIntegrationTests {
		// class body...
	}
----

+

[NOTE]
533
====
B
Brian Clozel 已提交
534 535 536 537 538
`@ActiveProfiles` provides support for __inheriting__ active bean definition profiles
declared by superclasses by default. It is also possible to resolve active bean
definition profiles programmatically by implementing a custom
<<testcontext-ctx-management-env-profiles-ActiveProfilesResolver,`ActiveProfilesResolver`>>
and registering it via the `resolver` attribute of `@ActiveProfiles`.
539
====
B
Brian Clozel 已提交
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759

+

See <<testcontext-ctx-management-env-profiles>> and the `@ActiveProfiles` javadocs
for examples and further details.

* `@TestPropertySource`

+

A class-level annotation that is used to configure the locations of properties files and
inlined properties to be added to the `Environment`'s set of `PropertySources` for an
`ApplicationContext` loaded for an integration test.

+ 

Test property sources have higher precedence than those loaded from the operating
system's environment or Java system properties as well as property sources added by the
application declaratively via `@PropertySource` or programmatically. Thus, test property
sources can be used to selectively override properties defined in system and application
property sources. Furthermore, inlined properties have higher precedence than properties
loaded from resource locations.

+

The following example demonstrates how to declare a properties file from the classpath.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	**@TestPropertySource**("/test.properties")
	public class MyIntegrationTests {
		// class body...
	}
----

+

The following example demonstrates how to declare _inlined_ properties.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	**@TestPropertySource**(properties = { "timezone = GMT", "port: 4242" })
	public class MyIntegrationTests {
		// class body...
	}
----

* `@DirtiesContext`

+

Indicates that the underlying Spring `ApplicationContext` has been __dirtied__ during
the execution of a test (i.e., modified or corrupted in some manner -- for example, by
changing the state of a singleton bean) and should be closed, regardless of whether the
test passed. When an application context is marked __dirty__, it is removed from the
testing framework's cache and closed. As a consequence, the underlying Spring container
will be rebuilt for any subsequent test that requires a context with the same
configuration metadata.

+

`@DirtiesContext` can be used 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.

+

The following examples explain when the context would be dirtied for various
configuration scenarios:

+

** After the current test class, when declared on a class with class mode set to
`AFTER_CLASS` (i.e., the default class mode).

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@DirtiesContext**
	public class ContextDirtyingTests {
		// some tests that result in the Spring container being dirtied
	}
----

+

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

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@DirtiesContext**(**classMode** = ClassMode.AFTER_EACH_TEST_METHOD)
	public class ContextDirtyingTests {
		// some tests that result in the Spring container being dirtied
	}
----

+

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

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@DirtiesContext**
	@Test
	public void testProcessWhichDirtiesAppCtx() {
		// some logic that results in the Spring container being dirtied
	}
----

+

If `@DirtiesContext` is used in a test whose context is configured as part of a context
hierarchy via `@ContextHierarchy`, the `hierarchyMode` flag can be used to control how
the context cache is cleared. By default an __exhaustive__ algorithm will be used that
clears the context cache including not only the current level but also all other context
hierarchies that share an ancestor context common to the current test; all
++ApplicationContext++s that reside in a sub-hierarchy of the common ancestor context
will be removed from the context cache and closed. If the __exhaustive__ algorithm is
overkill for a particular use case, the simpler __current level__ algorithm can be
specified instead, as seen below.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextHierarchy({
		@ContextConfiguration("/parent-config.xml"),
		@ContextConfiguration("/child-config.xml")
	})
	public class BaseTests {
		// class body...
	}

	public class ExtendedTests extends BaseTests {

		@Test
		@DirtiesContext(**hierarchyMode = HierarchyMode.CURRENT_LEVEL**)
		public void test() {
			// some logic that results in the child context being dirtied
		}
	}
----

+

For further details regarding the `EXHAUSTIVE` and `CURRENT_LEVEL` algorithms see the
`DirtiesContext.HierarchyMode` javadocs.

* `@TestExecutionListeners`

+

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

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	**@TestExecutionListeners**({CustomTestExecutionListener.class, AnotherTestExecutionListener.class})
	public class CustomTestExecutionListenerTests {
		// class body...
	}
----

+

`@TestExecutionListeners` supports __inherited__ listeners by default. See the javadocs
for an example and further details.

* `@TransactionConfiguration`

+

Defines class-level metadata for configuring transactional tests. Specifically, the bean
name of the `PlatformTransactionManager` that should be used to drive transactions can
be explicitly specified if there are multiple beans of type `PlatformTransactionManager`
in the test's `ApplicationContext` and 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`.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	**@TransactionConfiguration**(**transactionManager** = "txMgr", **defaultRollback** = false)
	public class CustomConfiguredTransactionalTests {
		// class body...
	}
----

+

[NOTE]
760
====
B
Brian Clozel 已提交
761 762 763 764 765 766 767
If the default conventions are sufficient for your test configuration, you can avoid
using `@TransactionConfiguration` altogether. In other words, if you have only one
transaction manager -- or if you have multiple transaction managers but the transaction
manager for tests is named "transactionManager" or specified via a
`TransactionManagementConfigurer` -- and if you want transactions to roll back
automatically, then there is no need to annotate your test class with
`@TransactionConfiguration`.
768
====
B
Brian Clozel 已提交
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918

+

* `@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.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@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.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@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.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@AfterTransaction**
	public void afterTransaction() {
		// logic to be executed after a transaction has ended
	}
----

* `@Sql`

+

Used to annotate a test class or test method to configure SQL scripts to be executed
against a given database during integration tests.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@Test
	**@Sql**({"/test-schema.sql", "/test-user-data.sql"})
	public void userTest {
		// execute code that relies on the test schema and test data
	}
----

+

See <<testcontext-executing-sql-declaratively>> for further details.

* `@SqlConfig`

+

Defines metadata that is used to determine how to parse and execute SQL scripts
configured via the `@Sql` annotation.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@Test
	@Sql(
		scripts = "/test-user-data.sql",
		config = **@SqlConfig**(commentPrefix = "`", separator = "@@")
	)
	public void userTest {
		// execute code that relies on the test data
	}
----

* `@SqlGroup`

+

A container annotation that aggregates several `@Sql` annotations. Can be used natively,
declaring several nested `@Sql` annotations. Can also be used in conjunction with Java
8's support for repeatable annotations, where `@Sql` can simply be declared several times
on the same class or method, implicitly generating this container annotation.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@Test
	**@SqlGroup**({
		@Sql(scripts = "/test-schema.sql", config = @SqlConfig(commentPrefix = "`")),
		@Sql("/test-user-data.sql")
	)}
	public void userTest {
		// execute code that uses the test schema and test data
	}
----


[[integration-testing-annotations-standard]]
==== 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`

.JSR-250 Lifecycle Annotations
[NOTE]
919
====
B
Brian Clozel 已提交
920 921 922 923 924 925 926 927 928 929 930
In the Spring TestContext Framework `@PostConstruct` and `@PreDestroy` may be used with
standard semantics on any application components configured in the `ApplicationContext`;
however, these lifecycle annotations have limited usage within an actual test class.

If a method within a test class is annotated with `@PostConstruct`, that method will be
executed before any __before__ methods of the underlying test framework (e.g., methods
annotated with JUnit's `@Before`), and that will apply for every test method in the test
class. On the other hand, if a method within a test class is annotated with
`@PreDestroy`, that method will __never__ be executed. Within a test class it is
therefore recommended to use test lifecycle callbacks from the underlying test framework
instead of `@PostConstruct` and `@PreDestroy`.
931
====
B
Brian Clozel 已提交
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378


[[integration-testing-annotations-junit]]
==== Spring JUnit Testing Annotations
The following annotations are __only__ supported when used in conjunction with the
<<testcontext-junit4-runner,SpringJUnit4ClassRunner>> or the
<<testcontext-support-classes-junit4,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.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@IfProfileValue**(**name**="java.vendor", **value**="Oracle Corporation")
	@Test
	public void testProcessWhichRunsOnlyOnOracleJvm() {
		// some logic that should run only on Java VMs from Oracle Corporation
	}
----

+

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:

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@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.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@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.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@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=...)`
preemptively fails the test if the test takes too long. Spring's `@Timed`, on the other
hand, 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.

+

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@Repeat**(10)
	@Test
	public void testProcessRepeatedly() {
		// ...
	}
----


[[integration-testing-annotations-meta]]
==== Meta-Annotation Support for Testing
As of Spring Framework 4.0, it is possible to use test-related annotations as
<<beans-meta-annotations,meta-annotations>> in order to create custom _composed annotations_
and reduce configuration duplication across a test suite.

Each of the following may be used as meta-annotations in conjunction with the
<<testcontext-framework,TestContext framework>>.

* `@ContextConfiguration`
* `@ContextHierarchy`
* `@ActiveProfiles`
* `@TestPropertySource`
* `@DirtiesContext`
* `@WebAppConfiguration`
* `@TestExecutionListeners`
* `@Transactional`
* `@BeforeTransaction`
* `@AfterTransaction`
* `@TransactionConfiguration`
* `@Rollback`
* `@Sql`
* `@SqlConfig`
* `@SqlGroup`
* `@Repeat`
* `@Timed`
* `@IfProfileValue`
* `@ProfileValueSourceConfiguration`

For example, if we discover that we are repeating the following configuration
across our JUnit-based test suite...

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@ContextConfiguration({"/app-config.xml", "/test-data-access-config.xml"})
	@ActiveProfiles("dev")
	@Transactional
	public class OrderRepositoryTests { }

	@RunWith(SpringJUnit4ClassRunner.class)
	@ContextConfiguration({"/app-config.xml", "/test-data-access-config.xml"})
	@ActiveProfiles("dev")
	@Transactional
	public class UserRepositoryTests { }
----

We can reduce the above duplication by introducing a custom _composed annotation_
that centralizes the common test configuration like this:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@Target(ElementType.TYPE)
	@Retention(RetentionPolicy.RUNTIME)
	@ContextConfiguration({"/app-config.xml", "/test-data-access-config.xml"})
	@ActiveProfiles("dev")
	@Transactional
	public @interface TransactionalDevTest { }
----

Then we can use our custom `@TransactionalDevTest` annotation to simplify the
configuration of individual test classes as follows:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@TransactionalDevTest
	public class OrderRepositoryTests { }

	@RunWith(SpringJUnit4ClassRunner.class)
	@TransactionalDevTest
	public class UserRepositoryTests { }
----



[[testcontext-framework]]
=== 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. 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 (<<testcontext-ctx-management,context management>>,
<<testcontext-fixture-di,dependency injection>>, <<testcontext-tx,transaction
management>>), <<testcontext-support-classes,support classes>>, and
<<integration-testing-annotations,annotation support>> sections.


[[testcontext-key-abstractions]]
==== 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 ++TestExecutionListener++s,
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 javadocs 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
  ++TestExecutionListener++s 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. See
  <<testcontext-tel-config>>.
* `ContextLoader`: Strategy interface introduced in Spring 2.5 for loading an
  `ApplicationContext` for an integration test managed by the Spring TestContext
  Framework.

+

Implement `SmartContextLoader` instead of this interface in order to provide support for
annotated classes, active bean definition profiles, test property sources, context
hierarchies, and ++WebApplicationContext++s.

* `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 resource
`locations`, annotated `classes`, or context `initializers`. Furthermore, a
`SmartContextLoader` can set active bean definition profiles and test property sources in
the context that it loads.

+

Spring provides the following implementations:

+

** `DelegatingSmartContextLoader`: one of two default loaders which delegates internally
to an `AnnotationConfigContextLoader`, a `GenericXmlContextLoader`, or a
`GenericGroovyXmlContextLoader` depending either on the configuration declared for the
test class or on the presence of default locations or default configuration classes.
Groovy support is only enabled if Groovy is on the classpath.
** `WebDelegatingSmartContextLoader`: one of two default loaders which delegates
internally to an `AnnotationConfigWebContextLoader`, a `GenericXmlWebContextLoader`, or a
`GenericGroovyXmlWebContextLoader` depending either on the configuration declared for the
test class or on the presence of default locations or default configuration classes. A
web `ContextLoader` will only be used if `@WebAppConfiguration` is present on the test
class. Groovy support is only enabled if Groovy is on the classpath.
** `AnnotationConfigContextLoader`: loads a standard `ApplicationContext` from
__annotated classes__.
** `AnnotationConfigWebContextLoader`: loads a `WebApplicationContext` from __annotated
classes__.
** `GenericGroovyXmlContextLoader`: loads a standard `ApplicationContext` from __resource
locations__ that are either Groovy scripts or XML configuration files.
** `GenericGroovyXmlWebContextLoader`: loads a `WebApplicationContext` from __resource
locations__ that are either Groovy scripts or XML configuration files.
** `GenericXmlContextLoader`: loads a standard `ApplicationContext` from XML __resource
locations__.
** `GenericXmlWebContextLoader`: loads a `WebApplicationContext` from XML __resource
locations__.
** `GenericPropertiesContextLoader`: loads a standard `ApplicationContext` 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.

[[testcontext-tel-config]]
==== TestExecutionListener configuration

Spring provides the following `TestExecutionListener` implementations that are registered
by default, exactly in this order.

* `ServletTestExecutionListener`: configures Servlet API mocks for a
  `WebApplicationContext`
* `DependencyInjectionTestExecutionListener`: provides dependency injection for the test
  instance
* `DirtiesContextTestExecutionListener`: handles the `@DirtiesContext` annotation
* `TransactionalTestExecutionListener`: provides transactional test execution with
  default rollback semantics
* `SqlScriptsTestExecutionListener`: executes SQL scripts configured via the `@Sql`
  annotation

[[testcontext-tel-config-registering-tels]]
===== Registering custom TestExecutionListeners

Custom ++TestExecutionListener++s can be registered for a test class and its subclasses
via the `@TestExecutionListeners` annotation. See
<<integration-testing-annotations,annotation support>> and the javadocs for
`@TestExecutionListeners` for details and examples.

[[testcontext-tel-config-automatic-discovery]]
===== Automatic discovery of default TestExecutionListeners

Registering custom ++TestExecutionListener++s via `@TestExecutionListeners` is suitable
for custom listeners that are used in limited testing scenarios; however, it can become
cumbersome if a custom listener needs to be used across a test suite. To address this
issue, Spring Framework 4.1 supports automatic discovery of _default_
`TestExecutionListener` implementations via the `SpringFactoriesLoader` mechanism.

Specifically, the `spring-test` module declares all core default
++TestExecutionListener++s under the
`org.springframework.test.context.TestExecutionListener` key in its
`META-INF/spring.factories` properties file. Third-party frameworks and developers can
contribute their own ++TestExecutionListener++s to the list of default listeners in the
same manner via their own `META-INF/spring.factories` properties file.

[[testcontext-tel-config-ordering]]
===== Ordering TestExecutionListeners

When the TestContext framework discovers default ++TestExecutionListeners++ via the
aforementioned `SpringFactoriesLoader` mechanism, the instantiated listeners are sorted
using Spring's `AnnotationAwareOrderComparator` which honors Spring's `Ordered` interface
and `@Order` annotation for ordering. `AbstractTestExecutionListener` and all default
++TestExecutionListener++s provided by Spring implement `Ordered` with appropriate
values. Third-party frameworks and developers should therefore make sure that their
_default_ ++TestExecutionListener++s are registered in the proper order by implementing
`Ordered` or declaring `@Order`. Consult the javadocs for the `getOrder()` methods of the
core default ++TestExecutionListener++s for details on what values are assigned to each
core listener.

[[testcontext-tel-config-merging]]
===== Merging TestExecutionListeners

If a custom `TestExecutionListener` is registered via `@TestExecutionListeners`, the
_default_ listeners will not be registered. In most common testing scenarios, this
effectively forces the developer to manually declare all default listeners in addition to
any custom listeners. The following listing demonstrates this style of configuration.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	@TestExecutionListeners({
		MyCustomTestExecutionListener.class,
		ServletTestExecutionListener.class,
		DependencyInjectionTestExecutionListener.class,
		DirtiesContextTestExecutionListener.class,
		TransactionalTestExecutionListener.class,
		SqlScriptsTestExecutionListener.class
	})
	public class MyTest {
		// class body...
	}
----

The challenge with this approach is that it requires that the developer know exactly
which listeners are registered by default. Moreover, the set of default listeners can
change from release to release -- for example, `SqlScriptsTestExecutionListener` was
introduced in Spring Framework 4.1. Furthermore, third-party frameworks like Spring
Security register their own default ++TestExecutionListener++s via the aforementioned
<<testcontext-tel-config-automatic-discovery, automatic discovery mechanism>>.

To avoid having to be aware of and re-declare **all** _default_ listeners, the
`mergeMode` attribute of `@TestExecutionListeners` can be set to
`MergeMode.MERGE_WITH_DEFAULTS`. `MERGE_WITH_DEFAULTS` indicates that locally declared
listeners should be merged with the default listeners. The merging algorithm ensures that
duplicates are removed from the list and that the resulting set of merged listeners is
sorted according to the semantics of `AnnotationAwareOrderComparator` as described in
<<testcontext-tel-config-ordering>>. If a listener implements `Ordered` or is annotated
with `@Order` it can influence the position in which it is merged with the defaults;
otherwise, locally declared listeners will simply be appended to the list of default
listeners when merged.

For example, if the `MyCustomTestExecutionListener` class in the previous example
configures its `order` value (for example, `500`) to be less than the order of the
`ServletTestExecutionListener` (which happens to be `1000`), the
`MyCustomTestExecutionListener` can then be automatically merged with the list of
defaults _in front of_ the `ServletTestExecutionListener`, and the previous example could
be replaced with the following.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	@TestExecutionListeners(
		listeners = MyCustomTestExecutionListener.class,
		mergeMode = MERGE_WITH_DEFAULTS,
	)
	public class MyTest {
		// class body...
	}
----


[[testcontext-ctx-management]]
==== 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` automatically.

.@Autowired ApplicationContext
[TIP]
S
Stephane Nicoll 已提交
1379
====
B
Brian Clozel 已提交
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
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:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@ContextConfiguration
	public class MyTest {

		**@Autowired**
		private ApplicationContext applicationContext;

		// class body...
	}
----

Similarly, if your test is configured to load a `WebApplicationContext`, you can inject
the web application context into your test as follows:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	**@WebAppConfiguration**
	@ContextConfiguration
	public class MyWebAppTest {
		**@Autowired**
		private WebApplicationContext wac;

		// class body...
	}
----

Dependency injection via `@Autowired` is provided by the
`DependencyInjectionTestExecutionListener` which is configured by default (see
<<testcontext-fixture-di>>).
S
Stephane Nicoll 已提交
1418
====
B
Brian Clozel 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507

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 annotated `classes`, the configured `ContextLoader` determines
how to load a context from a default location or default configuration classes. In
addition to context resource `locations` and annotated `classes`, an application context
can also be configured via application context `initializers`.

The following sections explain how to configure an `ApplicationContext` via XML
configuration files, annotated classes (typically `@Configuration` classes), or context
initializers using Spring's `@ContextConfiguration` annotation. Alternatively, you can
implement and configure your own custom `SmartContextLoader` for advanced use cases.

[[testcontext-ctx-management-xml]]
===== 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 or
relative 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__.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@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 declare additional
attributes in `@ContextConfiguration`, 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.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@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` and `GenericXmlWebContextLoader` detect
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"`.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	package com.example;

	@RunWith(SpringJUnit4ClassRunner.class)
	// ApplicationContext will be loaded from
	// "classpath:com/example/MyTest-context.xml"
	**@ContextConfiguration**
	public class MyTest {
		// class body...
	}
----

[[testcontext-ctx-management-groovy]]
===== Context configuration with Groovy scripts

To load an `ApplicationContext` for your tests using Groovy scripts that utilize the
<<groovy-bean-definition-dsl,Groovy Bean Definition DSL>>, annotate your test class with
`@ContextConfiguration` and configure the `locations` or `value` attribute with an array
that contains the resource locations of Groovy scripts. Resource lookup semantics for
Groovy scripts are the same as those described for <<testcontext-ctx-management-xml,XML
configuration files>>.


.Enabling Groovy script support
[TIP]
S
Stephane Nicoll 已提交
1508
====
B
Brian Clozel 已提交
1509 1510
Support for using Groovy scripts to load an `ApplicationContext` in the Spring
TestContext Framework is enabled automatically if Groovy is on the classpath.
S
Stephane Nicoll 已提交
1511
====
B
Brian Clozel 已提交
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	// ApplicationContext will be loaded from "/AppConfig.groovy" and
	// "/TestConfig.groovy" in the root of the classpath
	**@ContextConfiguration({"/AppConfig.groovy", "/TestConfig.Groovy"})**
	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 Groovy script.
Specifically, `GenericGroovyXmlContextLoader` and `GenericGroovyXmlWebContextLoader`
detect a default location based on the name of the test class. If your class is named
`com.example.MyTest`, the Groovy context loader will load your application context from
`"classpath:com/example/MyTestContext.groovy"`.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	package com.example;

	@RunWith(SpringJUnit4ClassRunner.class)
	// ApplicationContext will be loaded from
	// "classpath:com/example/MyTestContext.groovy"
	**@ContextConfiguration**
	public class MyTest {
		// class body...
	}
----

.Declaring XML config and Groovy scripts simultaneously
[TIP]
S
Stephane Nicoll 已提交
1548
====
B
Brian Clozel 已提交
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
Both XML configuration files and Groovy scripts can be declared simultaneously via the
`locations` or `value` attribute of `@ContextConfiguration`. If the path to a configured
resource location ends with `.xml` it will be loaded using an `XmlBeanDefinitionReader`;
otherwise it will be loaded using a `GroovyBeanDefinitionReader`.

The following listing demonstrates how to combine both in an integration test.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	// ApplicationContext will be loaded from
	// "/app-config.xml" and "/TestConfig.groovy"
	@ContextConfiguration({ "/app-config.xml", "/TestConfig.groovy" })
	public class MyTest {
		// class body...
	}
----
S
Stephane Nicoll 已提交
1567
====
B
Brian Clozel 已提交
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588

[[testcontext-ctx-management-javaconfig]]
===== Context configuration with annotated classes

To load an `ApplicationContext` for your tests using __annotated classes__ (see
<<beans-java>>), annotate your test class with `@ContextConfiguration` and configure the
`classes` attribute with an array that contains references to annotated classes.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	// ApplicationContext will be loaded from AppConfig and TestConfig
	**@ContextConfiguration(classes = {AppConfig.class, TestConfig.class})**
	public class MyTest {
		// class body...
	}
----

.Annotated Classes
[TIP]
S
Stephane Nicoll 已提交
1589
====
B
Brian Clozel 已提交
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
The term __annotated class__ can refer to any of the following.

* A class annotated with `@Configuration`
* A component (i.e., a class annotated with `@Component`, `@Service`, `@Repository`, etc.)
* A JSR-330 compliant class that is annotated with `javax.inject` annotations
* Any other class that contains `@Bean`-methods

Consult the javadocs of `@Configuration` and `@Bean` for further information regarding
the configuration and semantics of __annotated classes__, paying special attention to
the discussion of __`@Bean` Lite Mode__.
S
Stephane Nicoll 已提交
1600
====
B
Brian Clozel 已提交
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821

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` and
`AnnotationConfigWebContextLoader` will detect all `static` nested classes of the test class
that meet the requirements for configuration class implementations as specified in the
`@Configuration` javadocs. In the following example, the `OrderServiceTest` class
declares a `static` nested 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` nested configuration class if desired.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	// ApplicationContext will be loaded from the
	// static nested 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
		}

	}
----

[[testcontext-ctx-management-mixed-config]]
===== Mixing XML, Groovy scripts, and annotated classes

It may sometimes be desirable to mix XML configuration files, Groovy scripts, and
annotated classes (i.e., typically `@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.

Furthermore, some third-party frameworks (like Spring Boot) provide first-class support
for loading an `ApplicationContext` from different types of resources simultaneously
(e.g., XML configuration files, Groovy scripts, and `@Configuration` classes). The Spring
Framework historically has not supported this for standard deployments. Consequently,
most of the `SmartContextLoader` implementations that the Spring Framework delivers in
the `spring-test` module support only one resource type per test context; however, this
does not mean that you cannot use both. One exception to the general rule is that the
`GenericGroovyXmlContextLoader` and `GenericGroovyXmlWebContextLoader` support both XML
configuration files and Groovy scripts simultaneously. Furthermore, third-party
frameworks may choose to support the declaration of both `locations` and `classes` via
`@ContextConfiguration`, and with the standard testing support in the TestContext
framework, you have the following options.

If you want to use resource locations (e.g., XML or Groovy) __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 or Groovy scripts
you can include `@Configuration` classes via component scanning or define them as normal
Spring beans; 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 or Groovy 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.

[[testcontext-ctx-management-initializers]]
===== Context configuration with context initializers
To configure an `ApplicationContext` for your tests using context initializers, annotate
your test class with `@ContextConfiguration` and configure the `initializers` attribute
with an array that contains references to classes that implement
`ApplicationContextInitializer`. The declared context initializers will then be used to
initialize the `ConfigurableApplicationContext` that is loaded for your tests. Note that
the concrete `ConfigurableApplicationContext` type supported by each declared
initializer must be compatible with the type of `ApplicationContext` created by the
`SmartContextLoader` in use (i.e., typically a `GenericApplicationContext`).
Furthermore, the order in which the initializers are invoked depends on whether they
implement Spring's `Ordered` interface, are annotated with Spring's `@Order` or the
standard `@Priority` annotation.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	// ApplicationContext will be loaded from TestConfig
	// and initialized by TestAppCtxInitializer
	**@ContextConfiguration(
		classes = TestConfig.class,
		initializers = TestAppCtxInitializer.class)**
	public class MyTest {
		// class body...
	}
----

It is also possible to omit the declaration of XML configuration files or annotated
classes in `@ContextConfiguration` entirely and instead declare only
`ApplicationContextInitializer` classes which are then responsible for registering beans
in the context -- for example, by programmatically loading bean definitions from XML
files or configuration classes.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	// ApplicationContext will be initialized by EntireAppInitializer
	// which presumably registers beans in the context
	**@ContextConfiguration(initializers = EntireAppInitializer.class)**
	public class MyTest {
		// class body...
	}
----

[[testcontext-ctx-management-inheritance]]
===== Context configuration inheritance
`@ContextConfiguration` supports boolean `inheritLocations` and `inheritInitializers`
attributes that denote whether resource locations or annotated classes and context
initializers declared by superclasses should be __inherited__. The default value for
both flags is `true`. This means that a test class inherits the resource locations or
annotated classes as well as the context initializers declared by any superclasses.
Specifically, the resource locations or annotated classes for a test class are appended
to the list of resource locations or annotated classes declared by superclasses.
Similarly, the initializers for a given test class will be added to the set of
initializers defined by test superclasses. Thus, subclasses have the option
of __extending__ the resource locations, annotated classes, or context initializers.

If `@ContextConfiguration`'s `inheritLocations` or `inheritInitializers` attribute is
set to `false`, the resource locations or annotated classes and the context
initializers, respectively, for the test class __shadow__ and effectively replace the
configuration 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"__.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@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 annotated classes, the
`ApplicationContext` for `ExtendedTest` will be loaded from the `BaseConfig` __and__
`ExtendedConfig` classes, in that order. Beans defined in `ExtendedConfig` may therefore
override (i.e., replace) those defined in `BaseConfig`.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@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...
	}
----

In the following example that uses context initializers, the `ApplicationContext` for
`ExtendedTest` will be initialized using `BaseInitializer` __and__
`ExtendedInitializer`. Note, however, that the order in which the initializers are
invoked depends on whether they implement Spring's `Ordered` interface, are annotated
with Spring's `@Order` or the standard `@Priority` annotation.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	// ApplicationContext will be initialized by BaseInitializer
	**@ContextConfiguration(initializers = BaseInitializer.class)**
	public class BaseTest {
		// class body...
	}

	// ApplicationContext will be initialized by BaseInitializer
	// and ExtendedInitializer
	**@ContextConfiguration(initializers = ExtendedInitializer.class)**
	public class ExtendedTest extends BaseTest {
		// class body...
	}
----

[[testcontext-ctx-management-env-profiles]]
===== Context configuration with environment profiles
Spring 3.1 introduced first-class support in the framework for the notion of
environments and profiles (a.k.a., __bean definition profiles__), and integration tests
can be configured to activate particular bean definition profiles for various testing
scenarios. This is achieved by annotating a test class with the `@ActiveProfiles`
annotation and supplying a list of profiles that should be activated when loading the
`ApplicationContext` for the test.

[NOTE]
1822
====
B
Brian Clozel 已提交
1823 1824 1825
`@ActiveProfiles` may be used with any implementation of the new `SmartContextLoader`
SPI, but `@ActiveProfiles` is not supported with implementations of the older
`ContextLoader` SPI.
1826
====
B
Brian Clozel 已提交
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151

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

[source,xml,indent=0]
[subs="verbatim,quotes"]
----
	<!-- 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 profile="default">
			<jdbc:embedded-database id="dataSource">
				<jdbc:script
					location="classpath:com/bank/config/sql/schema.sql"/>
			</jdbc:embedded-database>
		</beans>

	</beans>
----

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	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 three times: in the __production__ profile, the
__dev__ profile, and the __default__ 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 populated with test data,
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.

It is sometimes useful to assign beans to a `default` profile. Beans within the default profile
are only included when no other profile is specifically activated. This can be used to define
_fallback_ beans to be used in the application's default state. For example, you may
explicitly provide a data source for `dev` and `production` profiles, but define an in-memory
data source as a default when neither of these is active.

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

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@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();
		}
	}
----

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@Configuration
	@Profile("production")
	public class JndiDataConfig {

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

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@Configuration
	@Profile("default")
	public class DefaultDataConfig {

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

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@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();
		}

	}
----

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	package com.bank.service;

	@RunWith(SpringJUnit4ClassRunner.class)
	@ContextConfiguration(classes = {
			TransferServiceConfig.class,
			StandaloneDataConfig.class,
			JndiDataConfig.class,
			DefaultDataConfig.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 four 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
* `DefaultDataConfig`: defines a `dataSource` for a default embedded database in case
  no profile is active

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

It is often the case that a single set of profiles is used across multiple test classes
within a given project. Thus, to avoid duplicate declarations of the `@ActiveProfiles`
annotation it is possible to declare `@ActiveProfiles` once on a base class, and
subclasses will automatically inherit the `@ActiveProfiles` configuration from the base
class. In the following example, the declaration of `@ActiveProfiles` (as well as other
annotations) has been moved to an abstract superclass, `AbstractIntegrationTest`.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	package com.bank.service;

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

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	package com.bank.service;

	// "dev" profile inherited from superclass
	public class TransferServiceTest extends AbstractIntegrationTest {

		@Autowired
		private TransferService transferService;

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

`@ActiveProfiles` also supports an `inheritProfiles` attribute that can be used to
disable the inheritance of active profiles.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	package com.bank.service;

	// "dev" profile overridden with "production"
	@ActiveProfiles(profiles = "production", inheritProfiles = false)
	public class ProductionTransferServiceTest extends AbstractIntegrationTest {
		// test body
	}
----

[[testcontext-ctx-management-env-profiles-ActiveProfilesResolver]]
Furthermore, it is sometimes necessary to resolve active profiles for tests
__programmatically__ instead of declaratively -- for example, based on:

* the current operating system
* whether tests are being executed on a continuous integration build server
* the presence of certain environment variables
* the presence of custom class-level annotations
* etc.

To resolve active bean definition profiles programmatically, simply implement a custom
`ActiveProfilesResolver` and register it via the `resolver` attribute of
`@ActiveProfiles`. The following example demonstrates how to implement and register a
custom `OperatingSystemActiveProfilesResolver`. For further information, refer to the
corresponding javadocs.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	package com.bank.service;

	// "dev" profile overridden programmatically via a custom resolver
	@ActiveProfiles(
		resolver = OperatingSystemActiveProfilesResolver.class,
		inheritProfiles = false)
	public class TransferServiceTest extends AbstractIntegrationTest {
		// test body
	}
----

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	package com.bank.service.test;

	public class OperatingSystemActiveProfilesResolver implements ActiveProfilesResolver {

		@Override
		String[] resolve(Class<?> testClass) {
			String profile = ...;
			// determine the value of profile based on the operating system
			return new String[] {profile};
		}
	}
----

[[testcontext-ctx-management-property-sources]]
===== Context configuration with test property sources

Spring 3.1 introduced first-class support in the framework for the notion of an
environment with a hierarchy of _property sources_, and since Spring 4.1 integration
tests can be configured with test-specific property sources. In contrast to the
`@PropertySource` annotation used on `@Configuration` classes, the `@TestPropertySource`
annotation can be declared on a test class to declare resource locations for test
properties files or _inlined_ properties. These test property sources will be added to
the `Environment`'s set of `PropertySources` for the `ApplicationContext` loaded for the
annotated integration test.

[NOTE]
2152
====
B
Brian Clozel 已提交
2153 2154 2155 2156 2157 2158 2159
`@TestPropertySource` may be used with any implementation of the `SmartContextLoader`
SPI, but `@TestPropertySource` is not supported with implementations of the older
`ContextLoader` SPI.

Implementations of `SmartContextLoader` gain access to merged test property source values
via the `getPropertySourceLocations()` and `getPropertySourceProperties()` methods in
`MergedContextConfiguration`.
2160
====
B
Brian Clozel 已提交
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496

*Declaring test property sources*

Test properties files can be configured via the `locations` or `value` attribute of
`@TestPropertySource` as shown in the following example.

Both traditional and XML-based properties file formats are supported -- for example,
`"classpath:/com/example/test.properties"` or `"file:///path/to/file.xml"`.

Each path will be interpreted as a Spring `Resource`. A plain path -- for example,
`"test.properties"` -- 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 will be treated
as an _absolute_ classpath resource, for example: `"/org/example/test.xml"`. A path which
references a URL (e.g., a path prefixed with `classpath:`, `file:`, `http:`, etc.) will
be loaded using the specified resource protocol. Resource location wildcards (e.g.
`**/*.properties`) are not permitted: each location must evaluate to exactly one
`.properties` or `.xml` resource.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	@TestPropertySource("/test.properties")
	public class MyIntegrationTests {
		// class body...
	}
----

_Inlined_ properties in the form of key-value pairs can be configured via the
`properties` attribute of `@TestPropertySource` as shown in the following example. All
key-value pairs will be added to the enclosing `Environment` as a single test
`PropertySource` with the highest precedence.

The supported syntax for key-value pairs is the same as the syntax defined for entries in
a Java properties file:

* `"key=value"`
* `"key:value"`
* `"key value"`

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	@TestPropertySource(properties = {"timezone = GMT", "port: 4242"})
	public class MyIntegrationTests {
		// class body...
	}
----

*Default properties file detection*

If `@TestPropertySource` is declared as an empty annotation (i.e., without explicit
values for the `locations` or `properties` attributes), an attempt will be made to detect
a _default_ properties file relative to the class that declared the annotation. For
example, if the annotated test class is `com.example.MyTest`, the corresponding default
properties file is `"classpath:com/example/MyTest.properties"`. If the default cannot be
detected, an `IllegalStateException` will be thrown.

*Precedence*

Test property sources have higher precedence than those loaded from the operating
system's environment or Java system properties as well as property sources added by the
application declaratively via `@PropertySource` or programmatically. Thus, test property
sources can be used to selectively override properties defined in system and application
property sources. Furthermore, inlined properties have higher precedence than properties
loaded from resource locations.

In the following example, the `timezone` and `port` properties as well as any properties
defined in `"/test.properties"` will override any properties of the same name that are
defined in system and application property sources. Furthermore, if the
`"/test.properties"` file defines entries for the `timezone` and `port` properties those
will be overridden by the _inlined_ properties declared via the `properties` attribute.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration
	@TestPropertySource(
		locations = "/test.properties",
		properties = {"timezone = GMT", "port: 4242"}
	)
	public class MyIntegrationTests {
		// class body...
	}
----

*Inheriting and overriding test property sources*

`@TestPropertySource` supports boolean `inheritLocations` and `inheritProperties`
attributes that denote whether resource locations for properties files and inlined
properties declared by superclasses should be __inherited__. The default value for both
flags is `true`. This means that a test class inherits the locations and inlined
properties declared by any superclasses. Specifically, the locations and inlined
properties for a test class are appended to the locations and inlined properties declared
by superclasses. Thus, subclasses have the option of __extending__ the locations and
inlined properties. Note that properties that appear later will __shadow__ (i.e..,
override) properties of the same name that appear earlier. In addition, the
aforementioned precedence rules apply for inherited test property sources as well.

If `@TestPropertySource`'s `inheritLocations` or `inheritProperties` attribute is set to
`false`, the locations or inlined properties, respectively, for the test class __shadow__
and effectively replace the configuration defined by superclasses.

In the following example, the `ApplicationContext` for `BaseTest` will be loaded using
only the `"base.properties"` file as a test property source. In contrast, the
`ApplicationContext` for `ExtendedTest` will be loaded using the `"base.properties"`
**and** `"extended.properties"` files as test property source locations.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@TestPropertySource("base.properties")
	@ContextConfiguration
	public class BaseTest {
		// ...
	}

	@TestPropertySource("extended.properties")
	@ContextConfiguration
	public class ExtendedTest extends BaseTest {
		// ...
	}
----

In the following example, the `ApplicationContext` for `BaseTest` will be loaded using only
the _inlined_ `key1` property. In contrast, the `ApplicationContext` for `ExtendedTest` will be
loaded using the _inlined_ `key1` and `key2` properties.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@TestPropertySource(properties = "key1 = value1")
	@ContextConfiguration
	public class BaseTest {
		// ...
	}

	@TestPropertySource(properties = "key2 = value2")
	@ContextConfiguration
	public class ExtendedTest extends BaseTest {
		// ...
	}
----

[[testcontext-ctx-management-web]]
===== Loading a WebApplicationContext
Spring 3.2 introduced support for loading a `WebApplicationContext` in integration
tests. To instruct the TestContext framework to load a `WebApplicationContext` instead
of a standard `ApplicationContext`, simply annotate the respective test class with
`@WebAppConfiguration`.

The presence of `@WebAppConfiguration` on your test class instructs the TestContext
framework (TCF) that a `WebApplicationContext` (WAC) should be loaded for your
integration tests. In the background the TCF makes sure that a `MockServletContext` is
created and supplied to your test's WAC. By default the base resource path for your
`MockServletContext` will be set to __"src/main/webapp"__. This is interpreted as a path
relative to the root of your JVM (i.e., normally the path to your project). If you're
familiar with the directory structure of a web application in a Maven project, you'll
know that __"src/main/webapp"__ is the default location for the root of your WAR. If you
need to override this default, simply provide an alternate path to the
`@WebAppConfiguration` annotation (e.g., `@WebAppConfiguration("src/test/webapp")`). If
you wish to reference a base resource path from the classpath instead of the file
system, just use Spring's __classpath:__ prefix.

Please note that Spring's testing support for `WebApplicationContexts` is on par with
its support for standard `ApplicationContexts`. When testing with a
`WebApplicationContext` you are free to declare either XML configuration files or
`@Configuration` classes via `@ContextConfiguration`. You are of course also free to use
any other test annotations such as `@TestExecutionListeners`,
`@TransactionConfiguration`, `@ActiveProfiles`, etc.

The following examples demonstrate some of the various configuration options for loading
a `WebApplicationContext`.

.Conventions
[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)

	// defaults to "file:src/main/webapp"
	@WebAppConfiguration

	// detects "WacTests-context.xml" in same package
	// or static nested @Configuration class
	@ContextConfiguration

	public class WacTests {
		//...
	}
----

The above example demonstrates the TestContext framework's support for __convention over
configuration__. If you annotate a test class with `@WebAppConfiguration` without
specifying a resource base path, the resource path will effectively default
to __"file:src/main/webapp"__. Similarly, if you declare `@ContextConfiguration` without
specifying resource `locations`, annotated `classes`, or context `initializers`, Spring
will attempt to detect the presence of your configuration using conventions
(i.e., __"WacTests-context.xml"__ in the same package as the `WacTests` class or static
nested `@Configuration` classes).

.Default resource semantics
[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)

	// file system resource
	@WebAppConfiguration("webapp")

	// classpath resource
	@ContextConfiguration("/spring/test-servlet-config.xml")

	public class WacTests {
		//...
	}
----

This example demonstrates how to explicitly declare a resource base path with
`@WebAppConfiguration` and an XML resource location with `@ContextConfiguration`. The
important thing to note here is the different semantics for paths with these two
annotations. By default, `@WebAppConfiguration` resource paths are file system based;
whereas, `@ContextConfiguration` resource locations are classpath based.

.Explicit resource semantics
[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)

	// classpath resource
	@WebAppConfiguration("classpath:test-web-resources")

	// file system resource
	@ContextConfiguration("file:src/main/webapp/WEB-INF/servlet-config.xml")

	public class WacTests {
		//...
	}
----

In this third example, we see that we can override the default resource semantics for
both annotations by specifying a Spring resource prefix. Contrast the comments in this
example with the previous example.

.[[testcontext-ctx-management-web-mocks]]Working with Web Mocks
--
To provide comprehensive web testing support, Spring 3.2 introduced a
`ServletTestExecutionListener` that is enabled by default. When testing against a
`WebApplicationContext` this <<testcontext-key-abstractions,TestExecutionListener>> sets
up default thread-local state via Spring Web's `RequestContextHolder` before each test
method and creates a `MockHttpServletRequest`, `MockHttpServletResponse`, and
`ServletWebRequest` based on the base resource path configured via
`@WebAppConfiguration`. `ServletTestExecutionListener` also ensures that the
`MockHttpServletResponse` and `ServletWebRequest` can be injected into the test
instance, and once the test is complete it cleans up thread-local state.

Once you have a `WebApplicationContext` loaded for your test you might find that you
need to interact with the web mocks -- for example, to set up your test fixture or to
perform assertions after invoking your web component. The following example demonstrates
which mocks can be autowired into your test instance. Note that the
`WebApplicationContext` and `MockServletContext` are both cached across the test suite;
whereas, the other mocks are managed per test method by the
`ServletTestExecutionListener`.

.Injecting mocks
[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@WebAppConfiguration
	@ContextConfiguration
	public class WacTests {

		@Autowired
		WebApplicationContext wac; // cached

		@Autowired
		MockServletContext servletContext; // cached

		@Autowired
		MockHttpSession session;

		@Autowired
		MockHttpServletRequest request;

		@Autowired
		MockHttpServletResponse response;

		@Autowired
		ServletWebRequest webRequest;

		//...
	}
----
--

[[testcontext-ctx-management-caching]]
===== Context caching

Once the TestContext framework loads an `ApplicationContext` (or `WebApplicationContext`)
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)__
* `contextInitializerClasses` __(from @ContextConfiguration)__
* `contextLoader` __(from @ContextConfiguration)__
* `parent` __(from @ContextHierarchy)__
* `activeProfiles` __(from @ActiveProfiles)__
* `propertySourceLocations` __(from @TestPropertySource)__
* `propertySourceProperties` __(from @TestPropertySource)__
* `resourceBasePath` __(from @WebAppConfiguration)__

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) but does not define `@WebAppConfiguration`, a different
`ContextLoader`, different active profiles, different context initializers, different
test property sources, or a different parent context, 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.

.Test suites and forked processes
[NOTE]
2497
====
B
Brian Clozel 已提交
2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
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, Maven, or Gradle it
is important to make sure that the build framework does not __fork__ between tests. For
example, if the
http://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html#forkMode[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.
2512
====
B
Brian Clozel 已提交
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680

Since having a large number of application contexts loaded within a given test suite can
cause the suite to take an unnecessarily long time to execute, it is often beneficial to
know exactly how many contexts have been loaded and cached. To view the statistics for
the underlying context cache, simply set the log level for the
`org.springframework.test.context.cache` logging category to `DEBUG`.

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 <<integration-testing-annotations-spring>>). 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.


[[testcontext-ctx-management-ctx-hierarchies]]
===== Context hierarchies

When writing integration tests that rely on a loaded Spring `ApplicationContext`, it is
often sufficient to test against a single context; however, there are times when it is
beneficial or even necessary to test against a hierarchy of ++ApplicationContext++s. For
example, if you are developing a Spring MVC web application you will typically have a
root `WebApplicationContext` loaded via Spring's `ContextLoaderListener` and a child
`WebApplicationContext` loaded via Spring's `DispatcherServlet`. This results in a
parent-child context hierarchy where shared components and infrastructure configuration
are declared in the root context and consumed in the child context by web-specific
components. Another use case can be found in Spring Batch applications where you often
have a parent context that provides configuration for shared batch infrastructure and a
child context for the configuration of a specific batch job.

As of Spring Framework 3.2.2, it is possible to write integration tests that use context
hierarchies by declaring context configuration via the `@ContextHierarchy` annotation,
either on an individual test class or within a test class hierarchy. If a context
hierarchy is declared on multiple classes within a test class hierarchy it is also
possible to merge or override the context configuration for a specific, named level in
the context hierarchy. When merging configuration for a given level in the hierarchy the
configuration resource type (i.e., XML configuration files or annotated classes) must be
consistent; otherwise, it is perfectly acceptable to have different levels in a context
hierarchy configured using different resource types.

The following JUnit-based examples demonstrate common configuration scenarios for
integration tests that require the use of context hierarchies.

.Single test class with context hierarchy
--
`ControllerIntegrationTests` represents a typical integration testing scenario for a
Spring MVC web application by declaring a context hierarchy consisting of two levels,
one for the __root__ WebApplicationContext (loaded using the `TestAppConfig`
`@Configuration` class) and one for the __dispatcher servlet__ `WebApplicationContext`
(loaded using the `WebConfig` `@Configuration` class). The `WebApplicationContext` that
is __autowired__ into the test instance is the one for the child context (i.e., the
lowest context in the hierarchy).

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@WebAppConfiguration
	@ContextHierarchy({
		@ContextConfiguration(classes = TestAppConfig.class),
		@ContextConfiguration(classes = WebConfig.class)
	})
	public class ControllerIntegrationTests {

		@Autowired
		private WebApplicationContext wac;

		// ...
	}
----

--


.Class hierarchy with implicit parent context
--
The following test classes define a context hierarchy within a test class hierarchy.
`AbstractWebTests` declares the configuration for a root `WebApplicationContext` in a
Spring-powered web application. Note, however, that `AbstractWebTests` does not declare
`@ContextHierarchy`; consequently, subclasses of `AbstractWebTests` can optionally
participate in a context hierarchy or simply follow the standard semantics for
`@ContextConfiguration`. `SoapWebServiceTests` and `RestWebServiceTests` both extend
`AbstractWebTests` and define a context hierarchy via `@ContextHierarchy`. The result is
that three application contexts will be loaded (one for each declaration of
`@ContextConfiguration`), and the application context loaded based on the configuration
in `AbstractWebTests` will be set as the parent context for each of the contexts loaded
for the concrete subclasses.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@WebAppConfiguration
	@ContextConfiguration("file:src/main/webapp/WEB-INF/applicationContext.xml")
	public abstract class AbstractWebTests {}

	@ContextHierarchy(@ContextConfiguration("/spring/soap-ws-config.xml")
	public class SoapWebServiceTests extends AbstractWebTests {}

	@ContextHierarchy(@ContextConfiguration("/spring/rest-ws-config.xml")
	public class RestWebServiceTests extends AbstractWebTests {}
----
--


.Class hierarchy with merged context hierarchy configuration
--
The following classes demonstrate the use of __named__ hierarchy levels in order to
__merge__ the configuration for specific levels in a context hierarchy. `BaseTests`
defines two levels in the hierarchy, `parent` and `child`. `ExtendedTests` extends
`BaseTests` and instructs the Spring TestContext Framework to merge the context
configuration for the `child` hierarchy level, simply by ensuring that the names
declared via `ContextConfiguration`'s `name` attribute are both `"child"`. The result is
that three application contexts will be loaded: one for `"/app-config.xml"`, one for
`"/user-config.xml"`, and one for `{"/user-config.xml", "/order-config.xml"}`. As with
the previous example, the application context loaded from `"/app-config.xml"` will be
set as the parent context for the contexts loaded from `"/user-config.xml"` and
`{"/user-config.xml", "/order-config.xml"}`.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@ContextHierarchy({
		@ContextConfiguration(name = "parent", locations = "/app-config.xml"),
		@ContextConfiguration(name = "child", locations = "/user-config.xml")
	})
	public class BaseTests {}

	@ContextHierarchy(
		@ContextConfiguration(name = "child", locations = "/order-config.xml")
	)
	public class ExtendedTests extends BaseTests {}
----
--

.Class hierarchy with overridden context hierarchy configuration
--
In contrast to the previous example, this example demonstrates how to __override__ the
configuration for a given named level in a context hierarchy by setting
++ContextConfiguration++'s `inheritLocations` flag to `false`. Consequently, the
application context for `ExtendedTests` will be loaded only from
`"/test-user-config.xml"` and will have its parent set to the context loaded from
`"/app-config.xml"`.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@ContextHierarchy({
		@ContextConfiguration(name = "parent", locations = "/app-config.xml"),
		@ContextConfiguration(name = "child", locations = "/user-config.xml")
	})
	public class BaseTests {}

	@ContextHierarchy(
		@ContextConfiguration(
			name = "child",
			locations = "/test-user-config.xml",
			inheritLocations = false
	))
	public class ExtendedTests extends BaseTests {}
----

.Dirtying a context within a context hierarchy
[NOTE]
2681
====
B
Brian Clozel 已提交
2682 2683 2684 2685 2686
If `@DirtiesContext` is used in a test whose context is configured as part of a context
hierarchy, the `hierarchyMode` flag can be used to control how the context cache is
cleared. For further details consult the discussion of `@DirtiesContext` in
<<integration-testing-annotations-spring,Spring Testing Annotations>> and the
`@DirtiesContext` javadocs.
2687
====
B
Brian Clozel 已提交
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
--


[[testcontext-fixture-di]]
==== 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]
S
Stephane Nicoll 已提交
2702
====
B
Brian Clozel 已提交
2703 2704 2705 2706

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.
S
Stephane Nicoll 已提交
2707
====
B
Brian Clozel 已提交
2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728

Because `@Autowired` is used to perform <<beans-factory-autowire, __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
<<integration-testing-goals,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]
2729
====
B
Brian Clozel 已提交
2730 2731 2732 2733 2734 2735 2736
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.
2737
====
B
Brian Clozel 已提交
2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814

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

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@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.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@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:

[source,xml,indent=0]
[subs="verbatim,quotes"]
----
	<?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.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]
S
Stephane Nicoll 已提交
2815
====
B
Brian Clozel 已提交
2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841
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.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// ...

		@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).
S
Stephane Nicoll 已提交
2842
====
B
Brian Clozel 已提交
2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138


[[testcontext-web-scoped-beans]]
==== Testing request and session scoped beans

<<beans-factory-scopes-other,Request and session scoped beans>> have been supported by
Spring for several years now, but it's always been a bit non-trivial to test them. As of
Spring 3.2 it's a breeze to test your request-scoped and session-scoped beans by
following these steps.

* Ensure that a `WebApplicationContext` is loaded for your test by annotating your test
  class with `@WebAppConfiguration`.
* Inject the mock request or session into your test instance and prepare your test
  fixture as appropriate.
* Invoke your web component that you retrieved from the configured
  `WebApplicationContext` (i.e., via dependency injection).
* Perform assertions against the mocks.

The following code snippet displays the XML configuration for a login use case. Note
that the `userService` bean has a dependency on a request-scoped `loginAction` bean.
Also, the `LoginAction` is instantiated using <<expressions,SpEL expressions>> that
retrieve the username and password from the current HTTP request. In our test, we will
want to configure these request parameters via the mock managed by the TestContext
framework.

.Request-scoped bean configuration
[source,xml,indent=0]
[subs="verbatim,quotes"]
----
	<beans>

		<bean id="userService"
				class="com.example.SimpleUserService"
				c:loginAction-ref="loginAction" />

		<bean id="loginAction" class="com.example.LoginAction"
				c:username="#{request.getParameter(''user'')}"
				c:password="#{request.getParameter(''pswd'')}"
				scope="request">
			<aop:scoped-proxy />
		</bean>

	</beans>
----

In `RequestScopedBeanTests` we inject both the `UserService` (i.e., the subject under
test) and the `MockHttpServletRequest` into our test instance. Within our
`requestScope()` test method we set up our test fixture by setting request parameters in
the provided `MockHttpServletRequest`. When the `loginUser()` method is invoked on our
`userService` we are assured that the user service has access to the request-scoped
`loginAction` for the current `MockHttpServletRequest` (i.e., the one we just set
parameters in). We can then perform assertions against the results based on the known
inputs for the username and password.

.Request-scoped bean test
[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@ContextConfiguration
	@WebAppConfiguration
	public class RequestScopedBeanTests {

		@Autowired UserService userService;
		@Autowired MockHttpServletRequest request;

		@Test
		public void requestScope() {

			request.setParameter("user", "enigma");
			request.setParameter("pswd", "$pr!ng");

			LoginResults results = userService.loginUser();

			// assert results
		}
	}
----

The following code snippet is similar to the one we saw above for a request-scoped bean;
however, this time the `userService` bean has a dependency on a session-scoped
`userPreferences` bean. Note that the `UserPreferences` bean is instantiated using a
SpEL expression that retrieves the __theme__ from the current HTTP session. In our test,
we will need to configure a theme in the mock session managed by the TestContext
framework.

.Session-scoped bean configuration
[source,xml,indent=0]
[subs="verbatim,quotes"]
----
	<beans>

		<bean id="userService"
				class="com.example.SimpleUserService"
				c:userPreferences-ref="userPreferences" />

		<bean id="userPreferences"
				class="com.example.UserPreferences"
				c:theme="#{session.getAttribute(''theme'')}"
				scope="session">
			<aop:scoped-proxy />
		</bean>

	</beans>
----

In `SessionScopedBeanTests` we inject the `UserService` and the `MockHttpSession` into
our test instance. Within our `sessionScope()` test method we set up our test fixture by
setting the expected "theme" attribute in the provided `MockHttpSession`. When the
`processUserPreferences()` method is invoked on our `userService` we are assured that
the user service has access to the session-scoped `userPreferences` for the current
`MockHttpSession`, and we can perform assertions against the results based on the
configured theme.

.Session-scoped bean test
[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@ContextConfiguration
	@WebAppConfiguration
	public class SessionScopedBeanTests {

		@Autowired UserService userService;
		@Autowired MockHttpSession session;

		@Test
		public void sessionScope() throws Exception {

			session.setAttribute("theme", "blue");

			Results results = userService.processUserPreferences();

			// assert results
		}
	}
----

[[testcontext-tx]]
==== Transaction management

In the TestContext framework, transactions are managed by the
`TransactionalTestExecutionListener` which is configured by default, even if you do not
explicitly declare `@TestExecutionListeners` on your test class. To enable support for
transactions, however, you must configure a `PlatformTransactionManager` bean in the
`ApplicationContext` that is loaded via `@ContextConfiguration` semantics (further
details are provided below). In addition, you must declare Spring's `@Transactional`
annotation either at the class or method level for your tests.

[[testcontext-tx-test-managed-transactions]]
===== Test-managed transactions

_Test-managed transactions_ are transactions that are managed _declaratively_ via the
`TransactionalTestExecutionListener` or _programmatically_ via `TestTransaction` (see
below). Such transactions should not be confused with _Spring-managed transactions_
(i.e., those managed directly by Spring within the `ApplicationContext` loaded for tests)
or _application-managed transactions_ (i.e., those managed programmatically within
application code that is invoked via tests). Spring-managed and application-managed
transactions will typically participate in test-managed transactions; however, caution
should be taken if Spring-managed or application-managed transactions are configured with
any _propagation_ type other than `REQUIRED` or `SUPPORTS` (see the discussion on
<<tx-propagation,transaction propagation>> for details).

[[testcontext-tx-enabling-transactions]]
===== Enabling and disabling transactions

Annotating a test method with `@Transactional` causes the test to be run within a
transaction that will, by default, be automatically rolled back after completion of the
test. If a test class is annotated with `@Transactional`, each test method within that
class hierarchy will be run within a transaction. Test methods that are not annotated
with `@Transactional` (at the class or method level) will not be run within a
transaction. Furthermore, tests that are annotated with `@Transactional` but have the
`propagation` type set to `NOT_SUPPORTED` will not be run within a transaction.

__Note that <<testcontext-support-classes-junit4,
`AbstractTransactionalJUnit4SpringContextTests`>> and
<<testcontext-support-classes-testng, `AbstractTransactionalTestNGSpringContextTests`>>
are preconfigured for transactional support at the class level.__

The following example demonstrates a common scenario for writing an integration test for
a Hibernate-based `UserRepository`. As explained in
<<testcontext-tx-rollback-and-commit-behavior>>, there is no need to clean up the
database after the `createUser()` method is executed since any changes made to the
database will be automatically rolled back by the `TransactionalTestExecutionListener`.
See <<testing-examples-petclinic>> for an additional example.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@ContextConfiguration(classes = TestConfig.class)
	@Transactional
	public class HibernateUserRepositoryTests {

		@Autowired
		HibernateUserRepository repository;

		@Autowired
		SessionFactory sessionFactory;

		JdbcTemplate jdbcTemplate;

		@Autowired
		public void setDataSource(DataSource dataSource) {
			this.jdbcTemplate = new JdbcTemplate(dataSource);
		}

		@Test
		public void createUser() {
			// track initial state in test database:
			final int count = countRowsInTable("user");

			User user = new User(...);
			repository.save(user);

			// Manual flush is required to avoid false positive in test
			sessionFactory.getCurrentSession().flush();
			assertNumUsers(count + 1);
		}

		protected int countRowsInTable(String tableName) {
			return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName);
		}

		protected void assertNumUsers(int expected) {
			assertEquals("Number of rows in the ''user'' table.", expected, countRowsInTable("user"));
		}
	}
----

[[testcontext-tx-rollback-and-commit-behavior]]
===== Transaction rollback and commit behavior

By default, test transactions will be automatically rolled back after completion of the
test; however, transactional commit and rollback behavior can be configured declaratively
via the class-level `@TransactionConfiguration` and method-level `@Rollback` annotations.
See the corresponding entries in the <<integration-testing-annotations,annotation
support>> section for further details.

[[testcontext-tx-programmatic-tx-mgt]]
===== Programmatic transaction management
As of Spring Framework 4.1, it is possible to interact with test-managed transactions
_programmatically_ via the static methods in `TestTransaction`. For example,
`TestTransaction` may be used within _test_ methods, _before_ methods, and _after_
methods to start or end the current test-managed transaction or to configure the current
test-managed transaction for rollback or commit. Support for `TestTransaction` is
automatically available whenever the `TransactionalTestExecutionListener` is enabled.

The following example demonstrates some of the features of `TestTransaction`. Consult the
javadocs for `TestTransaction` for further details.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@ContextConfiguration(classes = TestConfig.class)
	public class ProgrammaticTransactionManagementTests extends
			AbstractTransactionalJUnit4SpringContextTests {
	
		@Test
		public void transactionalTest() {
			// assert initial state in test database:
			assertNumUsers(2);

			deleteFromTables("user");

			// changes to the database will be committed!
			TestTransaction.flagForCommit();
			TestTransaction.end();
			assertFalse(TestTransaction.isActive());
			assertNumUsers(0);

			TestTransaction.start();
			// perform other actions against the database that will
			// be automatically rolled back after the test completes...
		}

		protected void assertNumUsers(int expected) {
			assertEquals("Number of rows in the ''user'' table.", expected, countRowsInTable("user"));
		}
	}
----

[[testcontext-tx-before-and-after-tx]]
===== Executing code outside of a transaction

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]
S
Stephane Nicoll 已提交
3139
====
B
Brian Clozel 已提交
3140 3141 3142 3143 3144
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 test methods that are not configured
to run within a transaction.
S
Stephane Nicoll 已提交
3145
====
B
Brian Clozel 已提交
3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213

[[testcontext-tx-mgr-config]]
===== Configuring a transaction manager

`TransactionalTestExecutionListener` expects a `PlatformTransactionManager` bean to be
defined in the Spring `ApplicationContext` for the test. In case there are multiple
instances of `PlatformTransactionManager` within the test's `ApplicationContext`,
`@TransactionConfiguration` supports configuring the bean name of the
`PlatformTransactionManager` that should be used to drive transactions. Alternatively, a
_qualifier_ may be declared via `@Transactional("myQualifier")`, or
`TransactionManagementConfigurer` can be implemented by an `@Configuration` class.
Consult the javadocs for `TestContextTransactionUtils.retrieveTransactionManager()` for
details on the algorithm used to look up a transaction manager in the test's
`ApplicationContext`.

[[testcontext-tx-annotation-demo]]
===== Demonstration of all transaction-related annotations

The following JUnit-based example displays a fictitious integration testing scenario
highlighting all transaction-related annotations. The example is **not** intended to
demonstrate best practices but rather to demonstrate how these annotations can be used.
Consult the <<integration-testing-annotations,annotation support>> section for further
information and configuration examples. <<testcontext-executing-sql-declaratively-tx,
Transaction management for `@Sql`>> contains an additional example using `@Sql` for
declarative SQL script execution with default transaction rollback semantics.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@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
		}

	}
----

[[testcontext-tx-false-positives]]
.Avoid false positives when testing ORM code
[NOTE]
S
Stephane Nicoll 已提交
3214
====
B
Brian Clozel 已提交
3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247
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__.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	// ...

	@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();
	}

	// ...
----
S
Stephane Nicoll 已提交
3248
====
B
Brian Clozel 已提交
3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560


[[testcontext-executing-sql]]
==== Executing SQL scripts

When writing integration tests against a relational database, it is often beneficial
to execute SQL scripts to modify the database schema or insert test data into tables.
The `spring-jdbc` module provides support for _initializing_ an embedded or existing
database by executing SQL scripts when the Spring `ApplicationContext` is loaded. See
<<jdbc-embedded-database-support>> and <<jdbc-embedded-database-dao-testing>> for
details.

Although it is very useful to initialize a database for testing _once_ when the
`ApplicationContext` is loaded, sometimes it is essential to be able to modify the
database _during_ integration tests. The following sections explain how to execute SQL
scripts programmatically and declaratively during integration tests.

[[testcontext-executing-sql-programmatically]]
===== Executing SQL scripts programmatically

Spring provides the following options for executing SQL scripts programmatically within
integration test methods.

* `org.springframework.jdbc.datasource.init.ScriptUtils`
* `org.springframework.jdbc.datasource.init.ResourceDatabasePopulator`
* `org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests`
* `org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests`

`ScriptUtils` provides a collection of static utility methods for working with SQL scripts
and is mainly intended for internal use within the framework. However, if you require
full control over how SQL scripts are parsed and executed, `ScriptUtils` may suit your
needs better than some of the other alternatives described below. Consult the javadocs for
individual methods in `ScriptUtils` for further details.

`ResourceDatabasePopulator` provides a simple object-based API for programmatically
populating, initializing, or cleaning up a database using SQL scripts defined in
external resources. `ResourceDatabasePopulator` provides options for configuring the
character encoding, statement separator, comment delimiters, and error handling flags
used when parsing and executing the scripts, and each of the configuration options has
a reasonable default value. Consult the javadocs for details on default values. To
execute the scripts configured in a `ResourceDatabasePopulator`, you can invoke either
the `populate(Connection)` method to execute the populator against a
`java.sql.Connection` or the `execute(DataSource)` method to execute the populator
against a `javax.sql.DataSource`. The following example specifies SQL scripts for a test
schema and test data, sets the statement separator to `"@@"`, and then executes the
scripts against a `DataSource`.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@Test
	public void databaseTest {
		ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
		populator.addScripts(
			new ClassPathResource("test-schema.sql"), 
			new ClassPathResource("test-data.sql"));
		populator.setSeparator("@@");
		populator.execute(this.dataSource);
		// execute code that uses the test schema and data
	}
----

Note that `ResourceDatabasePopulator` internally delegates to `ScriptUtils` for parsing
and executing SQL scripts. Similarly, the `executeSqlScript(..)` methods in
<<testcontext-support-classes-junit4, `AbstractTransactionalJUnit4SpringContextTests`>> and
<<testcontext-support-classes-testng, `AbstractTransactionalTestNGSpringContextTests`>>
internally use a `ResourceDatabasePopulator` for executing SQL scripts. Consult the javadocs
for the various `executeSqlScript(..)` methods for further details.


[[testcontext-executing-sql-declaratively]]
===== Executing SQL scripts declaratively with `@Sql`

In addition to the aforementioned mechanisms for executing SQL scripts
_programmatically_, SQL scripts can also be configured _declaratively_ in the Spring
TestContext Framework. Specifically, the `@Sql` annotation can be declared on a test
class or test method to configure the resource paths to SQL scripts that should be
executed against a given database either before or after an integration test method. Note
that method-level declarations override class-level declarations and that support for
`@Sql` is provided by the `SqlScriptsTestExecutionListener` which is enabled by default.

*Path resource semantics*

Each path will be interpreted as a Spring `Resource`. A plain path -- for example,
`"schema.sql"` -- 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 will be treated
as an _absolute_ classpath resource, for example: `"/org/example/schema.sql"`. A path
which references a URL (e.g., a path prefixed with `classpath:`, `file:`, `http:`, etc.)
will be loaded using the specified resource protocol.

The following example demonstrates how to use `@Sql` at the class level and at the method
level within a JUnit-based integration test class.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@ContextConfiguration
	@Sql("/test-schema.sql")
	public class DatabaseTests {

		@Test
		public void emptySchemaTest {
			// execute code that uses the test schema without any test data
		}

		@Test
		@Sql({"/test-schema.sql", "/test-user-data.sql"})
		public void userTest {
			// execute code that uses the test schema and test data
		}
	}
----

*Default script detection*

If no SQL scripts are specified, an attempt will be made to detect a `default` script
depending on where `@Sql` is declared. If a default cannot be detected, an
`IllegalStateException` will be thrown.

* __class-level declaration__: if the annotated test class is `com.example.MyTest`, the
	corresponding default script is `"classpath:com/example/MyTest.sql"`.
* __method-level declaration__: if the annotated test method is named `testMethod()` and is
	defined in the class `com.example.MyTest`, the corresponding default script is
	`"classpath:com/example/MyTest.testMethod.sql"`.

*Declaring multiple `@Sql` sets*

If multiple sets of SQL scripts need to be configured for a given test class or test
method but with different syntax configuration, different error handling rules, or
different execution phases per set, it is possible to declare multiple instances of
`@Sql`. With Java 8, `@Sql` can be used as a _repeatable_ annotation. Otherwise, the
`@SqlGroup` annotation can be used as an explicit container for declaring multiple
instances of `@Sql`.

The following example demonstrates the use of `@Sql` as a repeatable annotation using
Java 8. In this scenario the `test-schema.sql` script uses a different syntax for
single-line comments.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@Test
	@Sql(scripts = "/test-schema.sql", config = @SqlConfig(commentPrefix = "`"))
	@Sql("/test-user-data.sql")
	public void userTest {
		// execute code that uses the test schema and test data
	}
----

The following example is identical to the above except that the `@Sql` declarations are
grouped together within `@SqlGroup` for compatibility with Java 6 and Java 7.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@Test
	@SqlGroup({
		@Sql(scripts = "/test-schema.sql", config = @SqlConfig(commentPrefix = "`")),
		@Sql("/test-user-data.sql")
	)}
	public void userTest {
		// execute code that uses the test schema and test data
	}
----

*Script execution phases*

By default, SQL scripts will be executed _before_ the corresponding test method. However,
if a particular set of scripts needs to be executed _after_ the test method -- for
example, to clean up database state -- the `executionPhase` attribute in `@Sql` can be
used as seen in the following example. Note that `ISOLATED` and `AFTER_TEST_METHOD` are
statically imported from `Sql.TransactionMode` and `Sql.ExecutionPhase` respectively.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@Test
	@Sql(
		scripts = "create-test-data.sql",
		config = @SqlConfig(transactionMode = ISOLATED)
	)
	@Sql(
		scripts = "delete-test-data.sql",
		config = @SqlConfig(transactionMode = ISOLATED),
		executionPhase = AFTER_TEST_METHOD
	)
	public void userTest {
		// execute code that needs the test data to be committed
		// to the database outside of the test's transaction
	}
----

*Script configuration with `@SqlConfig`*

Configuration for script parsing and error handling can be configured via the
`@SqlConfig` annotation. When declared as a class-level annotation on an integration test
class, `@SqlConfig` serves as _global_ configuration for all SQL scripts within the test
class hierarchy. When declared directly via the `config` attribute of the `@Sql`
annotation, `@SqlConfig` serves as _local_ configuration for the SQL scripts declared
within the enclosing `@Sql` annotation. Every attribute in `@SqlConfig` has an implicit
default value which is documented in the javadocs of the corresponding attribute. Due to
the rules defined for annotation attributes in the Java Language Specification, it is
unfortunately not possible to assign a value of `null` to an annotation attribute. Thus,
in order to support overrides of inherited global configuration, `@SqlConfig` attributes
have an explicit default value of either `""` for Strings or `DEFAULT` for Enums. This
approach allows local declarations of `@SqlConfig` to selectively override individual
attributes from global declarations of `@SqlConfig` by providing a value other than `""`
or `DEFAULT`. Global `@SqlConfig` attributes are inherited whenever local `@SqlConfig`
attributes do not supply an explicit value other than `""` or `DEFAULT`. Explicit _local_
configuration therefore overrides _global_ configuration.

The configuration options provided by `@Sql` and `@SqlConfig` are equivalent to those
supported by `ScriptUtils` and `ResourceDatabasePopulator` but are a superset of those
provided by the `<jdbc:initialize-database/>` XML namespace element. Consult the javadocs
of individual attributes in `@Sql` and `@SqlConfig` for details.

[[testcontext-executing-sql-declaratively-tx]]
*Transaction management for `@Sql`*

By default, the `SqlScriptsTestExecutionListener` will infer the desired transaction
semantics for scripts configured via `@Sql`. Specifically, SQL scripts will be executed
without a transaction, within an existing Spring-managed transaction -- for example, a
transaction managed by the `TransactionalTestExecutionListener` for a test annotated with
`@Transactional` -- or within an isolated transaction, depending on the configured value
of the `transactionMode` attribute in `@SqlConfig` and the presence of a
`PlatformTransactionManager` in the test's `ApplicationContext`. As a bare minimum
however, a `javax.sql.DataSource` must be present in the test's `ApplicationContext`.

If the algorithms used by `SqlScriptsTestExecutionListener` to detect a `DataSource` and
`PlatformTransactionManager` and infer the transaction semantics do not suit your needs,
you may specify explicit names via the `dataSource` and `transactionManager` attributes
of `@SqlConfig`. Furthermore, the transaction propagation behavior can be controlled via
the `transactionMode` attribute of `@SqlConfig` -- for example, if scripts should be
executed in an isolated transaction. Although a thorough discussion of all supported
options for transaction management with `@Sql` is beyond the scope of this reference
manual, the javadocs for `@SqlConfig` and `SqlScriptsTestExecutionListener` provide
detailed information, and the following example demonstrates a typical testing scenario
using JUnit and transactional tests with `@Sql`. Note that there is no need to clean up
the database after the `usersTest()` method is executed since any changes made to the
database (either within the the test method or within the `/test-data.sql` script) will
be automatically rolled back by the `TransactionalTestExecutionListener` (see
<<testcontext-tx,transaction management>> for details).

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@ContextConfiguration(classes = TestDatabaseConfig.class)
	@Transactional
	public class TransactionalSqlScriptsTests {

		protected JdbcTemplate jdbcTemplate;

		@Autowired
		public void setDataSource(DataSource dataSource) {
			this.jdbcTemplate = new JdbcTemplate(dataSource);
		}

		@Test
		@Sql("/test-data.sql")
		public void usersTest() {
			// verify state in test database:
			assertNumUsers(2);
			// execute code that uses the test data...
		}

		protected int countRowsInTable(String tableName) {
			return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName);
		}

		protected void assertNumUsers(int expected) {
			assertEquals("Number of rows in the ''user'' table.", expected, countRowsInTable("user"));
		}
	}
----


[[testcontext-support-classes]]
==== TestContext Framework support classes

[[testcontext-support-classes-junit4]]
===== JUnit support classes
The `org.springframework.test.context.junit4` package provides the following support
classes for JUnit-based test cases.

* `AbstractJUnit4SpringContextTests`
* `AbstractTransactionalJUnit4SpringContextTests`

`AbstractJUnit4SpringContextTests` is an abstract base test class that integrates the
__Spring TestContext Framework__ with explicit `ApplicationContext` testing support in
a JUnit 4.9+ environment. When you extend `AbstractJUnit4SpringContextTests`, you can
access a `protected` `applicationContext` instance variable that can be used to perform
explicit bean lookups or to test the state of the context as a whole.

`AbstractTransactionalJUnit4SpringContextTests` is an abstract __transactional__ extension
of `AbstractJUnit4SpringContextTests` that adds some convenience functionality for JDBC
access. This class expects a `javax.sql.DataSource` bean and a `PlatformTransactionManager`
bean to be defined in the `ApplicationContext`. When you extend
`AbstractTransactionalJUnit4SpringContextTests` you can access a `protected` `jdbcTemplate`
instance variable that can be used 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 <<testcontext-tx-false-positives,false positives>>. As mentioned in
<<integration-testing-support-jdbc>>, `AbstractTransactionalJUnit4SpringContextTests`
also provides convenience methods which delegate to methods in `JdbcTestUtils` using the
aforementioned `jdbcTemplate`. Furthermore, `AbstractTransactionalJUnit4SpringContextTests`
provides an `executeSqlScript(..)` method for executing SQL scripts against the configured
`DataSource`.

[TIP]
S
Stephane Nicoll 已提交
3561
====
B
Brian Clozel 已提交
3562 3563 3564 3565
These classes are a convenience for extension. If you do not want your test classes to be
tied to a Spring-specific class hierarchy, you can configure your own custom test classes
by using `@RunWith(SpringJUnit4ClassRunner.class)`, `@ContextConfiguration`,
`@TestExecutionListeners`, and so on.
S
Stephane Nicoll 已提交
3566
====
B
Brian Clozel 已提交
3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626

[[testcontext-junit4-runner]]
===== Spring JUnit Runner
The __Spring TestContext Framework__ offers full integration with JUnit 4.9+ through a
custom runner (tested on JUnit 4.9 -- 4.11). 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`.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@TestExecutionListeners({})
	public class SimpleTest {

		@Test
		public void testMethod() {
			// execute test logic...
		}
	}
----

[[testcontext-support-classes-testng]]
===== TestNG support classes
The `org.springframework.test.context.testng` package provides the following support
classes for TestNG based test cases.

* `AbstractTestNGSpringContextTests`
* `AbstractTransactionalTestNGSpringContextTests`

`AbstractTestNGSpringContextTests` is an 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 a `protected` `applicationContext` instance variable that can be used to perform
explicit bean lookups or to test the state of the context as a whole.

`AbstractTransactionalTestNGSpringContextTests` is an abstract __transactional__ extension
of `AbstractTestNGSpringContextTests` that adds some convenience functionality for JDBC
access. This class expects a `javax.sql.DataSource` bean and a `PlatformTransactionManager`
bean to be defined in the `ApplicationContext`. When you extend
`AbstractTransactionalTestNGSpringContextTests` you can access a `protected` `jdbcTemplate`
instance variable that can be used 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 <<testcontext-tx-false-positives,false positives>>. As mentioned in
<<integration-testing-support-jdbc>>, `AbstractTransactionalTestNGSpringContextTests`
also provides convenience methods which delegate to methods in `JdbcTestUtils` using the
aforementioned `jdbcTemplate`. Furthermore, `AbstractTransactionalTestNGSpringContextTests`
provides an `executeSqlScript(..)` method for executing SQL scripts against the configured
`DataSource`.


[TIP]
S
Stephane Nicoll 已提交
3627
====
B
Brian Clozel 已提交
3628 3629 3630 3631 3632
These classes are a convenience for extension. If you do not want your test classes to be
tied to a Spring-specific class hierarchy, 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.
S
Stephane Nicoll 已提交
3633
====
B
Brian Clozel 已提交
3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236



[[spring-mvc-test-framework]]
=== Spring MVC Test Framework

.Standalone project
****
Before inclusion in Spring Framework 3.2, the Spring MVC Test framework had already
existed as a separate project on GitHub where it grew and evolved through actual use,
feedback, and the contribution of many.

The standalone https://github.com/spring-projects/spring-test-mvc[spring-test-mvc project]
is still available on GitHub and can be used in conjunction with Spring Framework 3.1.x.
Applications upgrading to 3.2 or later should replace the `spring-test-mvc` dependency with a
dependency on `spring-test`.

The `spring-test` module uses a different package `org.springframework.test.web` but
otherwise is nearly identical with two exceptions. One is support for features new in
3.2 (e.g. asynchronous web requests). The other relates to the options for creating a
`MockMvc` instance. In Spring Framework 3.2 and later, this can only be done through the
TestContext framework, which provides caching benefits for the loaded configuration.
****

The __Spring MVC Test framework__ provides first class JUnit support for testing client
and server-side Spring MVC code through a fluent API. Typically it loads the actual
Spring configuration through the __TestContext framework__ and always uses the
`DispatcherServlet` to process requests thus approximating full integration tests
without requiring a running Servlet container.

Client-side tests are `RestTemplate`-based and allow tests for code that relies on the
`RestTemplate` without requiring a running server to respond to the requests.


[[spring-mvc-test-server]]
==== Server-Side Tests
Before Spring Framework 3.2, the most likely way to test a Spring MVC controller was to
write a unit test that instantiates the controller, injects it with mock or stub
dependencies, and then calls its methods directly, using a `MockHttpServletRequest` and
`MockHttpServletResponse` where necessary.

Although this is pretty easy to do, controllers have many annotations, and much remains
untested. Request mappings, data binding, type conversion, and validation are just a few
examples of what isn't tested. Furthermore, there are other types of annotated methods
such as `@InitBinder`, `@ModelAttribute`, and `@ExceptionHandler` that get invoked as
part of request processing.

The idea behind Spring MVC Test is to be able to re-write those controller tests by
performing actual requests and generating responses, as they would be at runtime, along
the way invoking controllers through the Spring MVC `DispatcherServlet`. Controllers can
still be injected with mock dependencies, so tests can remain focused on the web layer.

Spring MVC Test builds on the familiar "mock" implementations of the Servlet API
available in the `spring-test` module. This allows performing requests and generating
responses without the need for running in a Servlet container. For the most part
everything should work as it does at runtime with the exception of JSP rendering, which
is not available outside a Servlet container. Furthermore, if you are familiar with how
the `MockHttpServletResponse` works, you'll know that forwards and redirects are not
actually executed. Instead "forwarded" and "redirected" URLs are saved and can be
asserted in tests. This means if you are using JSPs, you can verify the JSP page to
which the request was forwarded.

All other means of rendering including `@ResponseBody` methods and `View` types (besides
JSPs) such as Freemarker, Velocity, Thymeleaf, and others for rendering HTML, JSON, XML,
and so on should work as expected, and the response will contain the generated content.

Below is an example of a test requesting account information in JSON format:

[source,java,indent=0]
----
	import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
	import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

	@RunWith(SpringJUnit4ClassRunner.class)
	@WebAppConfiguration
	@ContextConfiguration("test-servlet-context.xml")
	public class ExampleTests {

		@Autowired
		private WebApplicationContext wac;

		private MockMvc mockMvc;

		@Before
		public void setup() {
			this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
		}

		@Test
		public void getAccount() throws Exception {
			this.mockMvc.perform(get("/accounts/1").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
				.andExpect(status().isOk())
				.andExpect(content().contentType("application/json"))
				.andExpect(jsonPath("$.name").value("Lee"));
		}

	}
----

The test relies on the `WebApplicationContext` support of the __TestContext framework__.
It loads Spring configuration from an XML configuration file located in the same package
as the test class (also supports JavaConfig) and injects the created
`WebApplicationContext` into the test so a `MockMvc` instance can be created with it.

The `MockMvc` is then used to perform a request to `"/accounts/1"` and verify the
resulting response status is 200, the response content type is `"application/json"`, and
response content has a JSON property called "name" with the value "Lee". JSON content is
inspected with the help of Jayway's https://github.com/jayway/JsonPath[JsonPath
project]. There are lots of other options for verifying the result of the performed
request and those will be discussed later.

[[spring-mvc-test-server-static-imports]]
===== Static Imports
The fluent API in the example above requires a few static imports such as
`MockMvcRequestBuilders.{asterisk}`, `MockMvcResultMatchers.{asterisk}`, 
and `MockMvcBuilders.{asterisk}`. An easy way to find these classes is to search for
types matching __"MockMvc*"__. If using Eclipse, be sure to add them as 
"favorite static members" in the Eclipse preferences under 
__Java -> Editor -> Content Assist -> Favorites__. That will allow use of content
assist after typing the first character of the static method name. Other IDEs (e.g.
IntelliJ) may not require any additional configuration. Just check the support for code
completion on static members.

[[spring-mvc-test-server-setup-options]]
===== Setup Options
The goal of server-side test setup is to create an instance of `MockMvc` that can be
used to perform requests. There are two main options.

The first option is to point to Spring MVC configuration through the __TestContext
framework__, which loads the Spring configuration and injects a `WebApplicationContext`
into the test to use to create a `MockMvc`:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@WebAppConfiguration
	@ContextConfiguration("my-servlet-context.xml")
	public class MyWebTests {

		@Autowired
		private WebApplicationContext wac;

		private MockMvc mockMvc;

		@Before
		public void setup() {
			this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
		}

		// ...

	}
----

The second option is to simply register a controller instance without loading any Spring
configuration. Instead basic Spring MVC configuration suitable for testing annotated
controllers is automatically created. The created configuration is comparable to that of
the MVC JavaConfig (and the MVC namespace) and can be customized to a degree through
builder-style methods:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	public class MyWebTests {

		private MockMvc mockMvc;

		@Before
		public void setup() {
			this.mockMvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();
		}

		// ...

	}
----

Which option should you use?

The __"webAppContextSetup"__ loads the actual Spring MVC configuration resulting in a
more complete integration test. Since the __TestContext framework__ caches the loaded
Spring configuration, it helps to keep tests running fast even as more tests get added.
Furthermore, you can inject mock services into controllers through Spring configuration,
in order to remain focused on testing the web layer. Here is an example of declaring a
mock service with Mockito:

[source,xml,indent=0]
[subs="verbatim,quotes"]
----
	<bean id="accountService" class="org.mockito.Mockito" factory-method="mock">
		<constructor-arg value="org.example.AccountService"/>
	</bean>
----

Then you can inject the mock service into the test in order set up and verify
expectations:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	@RunWith(SpringJUnit4ClassRunner.class)
	@WebAppConfiguration
	@ContextConfiguration("test-servlet-context.xml")
	public class AccountTests {

		@Autowired
		private WebApplicationContext wac;

		private MockMvc mockMvc;

		@Autowired
		private AccountService accountService;

		// ...

	}
----

The __"standaloneSetup"__ on the other hand is a little closer to a unit test. It tests
one controller at a time, the controller can be injected with mock dependencies
manually, and it doesn't involve loading Spring configuration. Such tests are more
focused in style and make it easier to see which controller is being tested, whether any
specific Spring MVC configuration is required to work, and so on. The "standaloneSetup"
is also a very convenient way to write ad-hoc tests to verify some behavior or to debug
an issue.

Just like with integration vs unit testing, there is no right or wrong answer. Using the
"standaloneSetup" does imply the need for some additional "webAppContextSetup" tests to
verify the Spring MVC configuration. Alternatively, you can decide write all tests with
"webAppContextSetup" and always test against actual Spring MVC configuration.

[[spring-mvc-test-server-performing-requests]]
===== Performing Requests
To perform requests, use the appropriate HTTP method and additional builder-style
methods corresponding to properties of `MockHttpServletRequest`. For example:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	mockMvc.perform(post("/hotels/{id}", 42).accept(MediaType.APPLICATION_JSON));
----

In addition to all the HTTP methods, you can also perform file upload requests, which
internally creates an instance of `MockMultipartHttpServletRequest`:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	mockMvc.perform(fileUpload("/doc").file("a1", "ABC".getBytes("UTF-8")));
----

Query string parameters can be specified in the URI template:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	mockMvc.perform(get("/hotels?foo={foo}", "bar"));
----

Or by adding Servlet request parameters:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	mockMvc.perform(get("/hotels").param("foo", "bar"));
----

If application code relies on Servlet request parameters, and doesn't check the query
string, as is most often the case, then it doesn't matter how parameters are added. Keep
in mind though that parameters provided in the URI template will be decoded while
parameters provided through the `param(...)` method are expected to be decoded.

In most cases it's preferable to leave out the context path and the Servlet path from
the request URI. If you must test with the full request URI, be sure to set the
`contextPath` and `servletPath` accordingly so that request mappings will work:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	mockMvc.perform(get("/app/main/hotels/{id}").contextPath("/app").servletPath("/main"))
----

Looking at the above example, it would be cumbersome to set the contextPath and
servletPath with every performed request. That's why you can define default request
properties when building the `MockMvc`:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	public class MyWebTests {

		private MockMvc mockMvc;

		@Before
		public void setup() {
			mockMvc = standaloneSetup(new AccountController())
				.defaultRequest(get("/")
				.contextPath("/app").servletPath("/main")
				.accept(MediaType.APPLICATION_JSON).build();
		}
----

The above properties will apply to every request performed through the `MockMvc`. If the
same property is also specified on a given request, it will override the default value.
That is why, the HTTP method and URI don't matter, when setting default request
properties, since they must be specified on every request.

[[spring-mvc-test-server-defining-expectations]]
===== Defining Expectations
Expectations can be defined by appending one or more `.andExpect(..)` after call to
perform the request:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	mockMvc.perform(get("/accounts/1")).andExpect(status().isOk());
----

`MockMvcResultMatchers.*` defines a number of static members, some of which return types
with additional methods, for asserting the result of the performed request. The
assertions fall in two general categories.

The first category of assertions verify properties of the response, i.e the response
status, headers, and content. Those are the most important things to test for.

The second category of assertions go beyond the response, and allow inspecting Spring
MVC specific constructs such as which controller method processed the request, whether
an exception was raised and handled, what the content of the model is, what view was
selected, what flash attributes were added, and so on. It is also possible to verify
Servlet specific constructs such as request and session attributes. The following test
asserts that binding/validation failed:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	mockMvc.perform(post("/persons"))
		.andExpect(status().isOk())
		.andExpect(model().attributeHasErrors("person"));
----

Many times when writing tests, it's useful to dump the result of the performed request.
This can be done as follows, where `print()` is a static import from
`MockMvcResultHandlers`:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	mockMvc.perform(post("/persons"))
		.andDo(print())
		.andExpect(status().isOk())
		.andExpect(model().attributeHasErrors("person"));
----

As long as request processing causes an unhandled exception, the `print()` method will
print all the available result data to `System.out`.

In some cases, you may want to get direct access to the result and verify something that
cannot be verified otherwise. This can be done by appending `.andReturn()` at the end
after all expectations:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	MvcResult mvcResult = mockMvc.perform(post("/persons")).andExpect(status().isOk()).andReturn();
	// ...
----

When all tests repeat the same expectations, you can define the common expectations once
when building the `MockMvc`:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	standaloneSetup(new SimpleController())
		.alwaysExpect(status().isOk())
		.alwaysExpect(content().contentType("application/json;charset=UTF-8"))
		.build()
----

Note that the expectation is __always__ applied and cannot be overridden without
creating a separate `MockMvc` instance.

When JSON response content contains hypermedia links created with
https://github.com/spring-projects/spring-hateoas[Spring HATEOAS], the resulting links can
be verified:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	mockMvc.perform(get("/people").accept(MediaType.APPLICATION_JSON))
		.andExpect(jsonPath("$.links[?(@.rel == ''self'')].href").value("http://localhost:8080/people"));
----

When XML response content contains hypermedia links created with
https://github.com/spring-projects/spring-hateoas[Spring HATEOAS], the resulting links can
be verified:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	Map<String, String> ns = Collections.singletonMap("ns", "http://www.w3.org/2005/Atom");
	mockMvc.perform(get("/handle").accept(MediaType.APPLICATION_XML))
		.andExpect(xpath("/person/ns:link[@rel=''self'']/@href", ns).string("http://localhost:8080/people"));
----

[[spring-mvc-test-server-filters]]
===== Filter Registrations
When setting up a `MockMvc`, you can register one or more `Filter` instances:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	mockMvc = standaloneSetup(new PersonController()).addFilters(new CharacterEncodingFilter()).build();
----

Registered filters will be invoked through `MockFilterChain` from `spring-test` and the
last filter will delegates to the `DispatcherServlet`.

[[spring-mvc-test-server-resources]]
===== Further Server-Side Test Examples
The framework's own tests include
https://github.com/spring-projects/spring-framework/tree/master/spring-test/src/test/java/org/springframework/test/web/servlet/samples[many
sample tests] intended to demonstrate how to use Spring MVC Test. Browse these examples
for further ideas. Also the
https://github.com/spring-projects/spring-mvc-showcase[spring-mvc-showcase] has full test
coverage based on Spring MVC Test.


[[spring-mvc-test-client]]
==== Client-Side REST Tests
Client-side tests are for code using the `RestTemplate`. The goal is to define expected
requests and provide "stub" responses:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	RestTemplate restTemplate = new RestTemplate();

	MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
	mockServer.expect(requestTo("/greeting")).andRespond(withSuccess("Hello world", MediaType.TEXT_PLAIN));

	// use RestTemplate ...

	mockServer.verify();
----

In the above example, `MockRestServiceServer` -- the central class for client-side REST
tests -- configures the `RestTemplate` with a custom `ClientHttpRequestFactory` that
asserts actual requests against expectations and returns "stub" responses. In this case
we expect a single request to "/greeting" and want to return a 200 response with
"text/plain" content. We could define as many additional requests and stub responses as
necessary.

Once expected requests and stub responses have been defined, the `RestTemplate` can be
used in client-side code as usual. At the end of the tests `mockServer.verify()` can be
used to verify that all expected requests were performed.

[[spring-mvc-test-client-static-imports]]
===== Static Imports
Just like with server-side tests, the fluent API for client-side tests requires a few
static imports. Those are easy to find by searching __"MockRest*"__. Eclipse users
should add `"MockRestRequestMatchers.{asterisk}"` and `"MockRestResponseCreators.{asterisk}"`
as "favorite static members" in the Eclipse preferences under 
__Java -> Editor -> Content Assist -> Favorites__.
That allows using content assist after typing the first character of the
static method name. Other IDEs (e.g. IntelliJ) may not require any additional
configuration. Just check the support for code completion on static members.

[[spring-mvc-test-client-resources]]
===== Further Examples of Client-side REST Tests
Spring MVC Test's own tests include
https://github.com/spring-projects/spring-framework/tree/master/spring-test/src/test/java/org/springframework/test/web/client/samples[example
tests] of client-side REST tests.



[[testing-examples-petclinic]]
=== PetClinic Example

The PetClinic application, available on
https://github.com/spring-projects/spring-petclinic[GitHub], illustrates several features
of the __Spring TestContext Framework__ in a JUnit environment. Most test functionality
is included in the `AbstractClinicTests`, for which a partial listing is shown below:

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	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 `getVets()` 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`.

[source,java,indent=0]
[subs="verbatim,quotes"]
----
	**@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.




[[testing-resources]]
== Further Resources
Consult the following resources for more information about testing:

* http://www.junit.org/[JUnit]: "__A programmer-oriented testing framework for Java__".
  Used by the Spring Framework in its test suite.
* http://testng.org/[TestNG]: A testing framework inspired by JUnit with added support
  for annotations, test groups, data-driven testing, distributed testing, etc.
* http://www.mockobjects.com/[MockObjects.com]: Web site dedicated to mock objects, a
  technique for improving the design of code within test-driven development.
* http://en.wikipedia.org/wiki/Mock_Object["Mock Objects"]: Article in Wikipedia.
* http://www.easymock.org/[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.
* http://www.jmock.org/[JMock]: Library that supports test-driven development of Java
  code with mock objects.
* http://mockito.org/[Mockito]: Java mock library based on the
  http://xunitpatterns.com/Test%20Spy.html[test spy] pattern.
* http://dbunit.sourceforge.net/[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.
* http://grinder.sourceforge.net/[The Grinder]: Java load testing framework.