From 95ff22cb7e4dcb5b133997a1e5f3d347109232f2 Mon Sep 17 00:00:00 2001 From: Jay Bryant Date: Thu, 30 Aug 2018 10:29:17 -0500 Subject: [PATCH] Edit the testing part of the reference documentation I edited for spelling, punctuation, grammar, usage, and corporate voice. I also added cross-references and links to the Javadoc. --- src/docs/asciidoc/core/core-beans.adoc | 2 +- src/docs/asciidoc/testing-webtestclient.adoc | 150 +- src/docs/asciidoc/testing.adoc | 3733 ++++++++++-------- 3 files changed, 2278 insertions(+), 1607 deletions(-) diff --git a/src/docs/asciidoc/core/core-beans.adoc b/src/docs/asciidoc/core/core-beans.adoc index 9c8f065008..96c25058f0 100644 --- a/src/docs/asciidoc/core/core-beans.adoc +++ b/src/docs/asciidoc/core/core-beans.adoc @@ -8420,7 +8420,7 @@ the `Environment` or ,declaratively, by using the `spring.profiles.default` prop [[beans-property-source-abstraction]] -=== `PropertySource` abstraction +=== `PropertySource` Abstraction Spring's `Environment` abstraction provides search operations over a configurable hierarchy of property sources. Consider the following listing: diff --git a/src/docs/asciidoc/testing-webtestclient.adoc b/src/docs/asciidoc/testing-webtestclient.adoc index f8f20cc329..9c8243f68a 100644 --- a/src/docs/asciidoc/testing-webtestclient.adoc +++ b/src/docs/asciidoc/testing-webtestclient.adoc @@ -3,16 +3,12 @@ `WebTestClient` is a thin shell around <>, using it to perform requests and exposing a dedicated, fluent API for verifying responses. -`WebTestClient` bind to a WebFlux application using a +`WebTestClient` binds to a WebFlux application by using a <>, or it can test any web server over an HTTP connection. - -[TIP] -==== -Kotlin users, please see <> +TIP: Kotlin users: See <> related to use of the `WebTestClient`. -==== @@ -26,48 +22,53 @@ a URL to connect to a running server. [[webtestclient-controller-config]] -=== Bind to controller +=== Bind to Controller -Use this server setup to test one `@Controller` at a time: +The following example shows how to create a server setup to test one `@Controller` at a time: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- client = WebTestClient.bindToController(new TestController()).build(); ---- +==== -The above loads the <> and -registers the given controller. The resulting WebFlux application will be tested -without an HTTP server using mock request and response objects. There are more methods -on the builder to customize the default WebFlux Java config. +The preceding example loads the <> and +registers the given controller. The resulting WebFlux application is tested +without an HTTP server by using mock request and response objects. There are more methods +on the builder to customize the default WebFlux Java configuration. [[webtestclient-fn-config]] -=== Bind to RouterFunction +=== Bind to Router Function -Use this option to set up a server from a +The folloiwng example shows how to set up a server from a <>: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- RouterFunction route = ... client = WebTestClient.bindToRouterFunction(route).build(); ---- +==== -Internally the provided configuration is passed to `RouterFunctions.toWebHandler`. -The resulting WebFlux application will be tested without an HTTP server using mock +Internally, the configuration is passed to `RouterFunctions.toWebHandler`. +The resulting WebFlux application is tested without an HTTP server by using mock request and response objects. [[webtestclient-context-config]] -=== Bind to ApplicationContext +=== Bind to `ApplicationContext` -Use this option to setup a server from the Spring configuration of your application, or +The following example shows how to setup a server from the Spring configuration of your application or some subset of it: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- @@ -90,35 +91,40 @@ some subset of it: <1> Specify the configuration to load <2> Inject the configuration <3> Create the `WebTestClient` +==== -Internally the provided configuration is passed to `WebHttpHandlerBuilder` to set up -the request processing chain, see +Internally, the configuration is passed to `WebHttpHandlerBuilder` to set up +the request processing chain. See <> for more details. The -resulting WebFlux application will be tested without an HTTP server using mock request +resulting WebFlux application is tested without an HTTP server by using mock request and response objects. [[webtestclient-server-config]] -=== Bind to server +=== Bind to Server -This server setup option allows you to connect to a running server: +The following server setup option lets you connect to a running server: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- client = WebTestClient.bindToServer().baseUrl("http://localhost:8080").build(); ---- +==== + [[webtestclient-client-config]] -=== Client builder +=== Client Builder -In addition to the server setup options above, you can also configure client -options including base URL, default headers, client filters, and others. These options +In addition to the server setup options described earlier, you can also configure client +options, including base URL, default headers, client filters, and others. These options are readily available following `bindToServer`. For all others, you need to use -`configureClient()` to transition from server to client configuration as shown below: +`configureClient()` to transition from server to client configuration, as follows: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- @@ -127,19 +133,20 @@ are readily available following `bindToServer`. For all others, you need to use .baseUrl("/test") .build(); ---- - +==== [[webtestclient-tests]] -== Writing tests +== Writing Tests `WebTestClient` is a thin shell around <>. -It provides an identical API up to the point of performing a request via `exchange()`. +It provides an identical API up to the point of performing a request by using `exchange()`. What follows after `exchange()` is a chained API workflow to verify responses. -Typically you start by asserting the response status and headers: +Typically, you start by asserting the response status and headers, as follows: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- @@ -150,15 +157,17 @@ Typically you start by asserting the response status and headers: .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) // ... ---- +==== Then you specify how to decode and consume the response body: -* `expectBody(Class)` -- decode to single object. -* `expectBodyList(Class)` -- decode and collect objects to `List`. -* `expectBody()` -- decode to `byte[]` for <> or empty body. +* `expectBody(Class)`: Decode to single object. +* `expectBodyList(Class)`: Decode and collect objects to `List`. +* `expectBody()`: Decode to `byte[]` for <> or an empty body. -Then you can use built-in assertions for the body. Here is one example: +Then you can use built-in assertions for the body. The following example shows one way to do so: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- @@ -167,9 +176,11 @@ Then you can use built-in assertions for the body. Here is one example: .expectStatus().isOk() .expectBodyList(Person.class).hasSize(3).contains(person); ---- +==== -You can go beyond the built-in assertions and create your own: +You can also go beyond the built-in assertions and create your own, as the following example shows: +==== ---- client.get().uri("/persons/1") .exchange() @@ -179,9 +190,11 @@ You can go beyond the built-in assertions and create your own: // custom assertions (e.g. AssertJ)... }); ---- +==== -You can also exit the workflow and get a result: +You can also exit the workflow and get a result, as follows: +==== ---- EntityExchangeResult result = client.get().uri("/persons/1") .exchange() @@ -189,22 +202,22 @@ You can also exit the workflow and get a result: .expectBody(Person.class) .returnResult(); ---- +==== -[TIP] -==== -When you need to decode to a target type with generics, look for the overloaded methods +TIP: When you need to decode to a target type with generics, look for the overloaded methods that accept -{api-spring-framework}/core/ParameterizedTypeReference.html[ParameterizedTypeReference] +{api-spring-framework}/core/ParameterizedTypeReference.html[`ParameterizedTypeReference`] instead of `Class`. -==== + [[webtestclient-no-content]] -=== No content +=== No Content -If the response has no content, or you don't care if it does, use `Void.class` which ensures -that resources are released: +If the response has no content (or you do not care if it does) use `Void.class`, which ensures +that resources are released. The following example shows how to do so: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- @@ -213,9 +226,11 @@ that resources are released: .expectStatus().isNotFound() .expectBody(Void.class); ---- +==== -Or if you want to assert there is no response content, use this: +Alternatively, if you want to assert there is no response content, you can use code similar to the following: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- @@ -225,16 +240,18 @@ Or if you want to assert there is no response content, use this: .expectStatus().isCreated() .expectBody().isEmpty(); ---- +==== [[webtestclient-json]] -=== JSON content +=== JSON Content -When you use `expectBody()` the response is consumed as a `byte[]`. This is useful for -raw content assertions. For example you can use -http://jsonassert.skyscreamer.org[JSONAssert] to verify JSON content: +When you use `expectBody()`, the response is consumed as a `byte[]`. This is useful for +raw content assertions. For example, you can use +http://jsonassert.skyscreamer.org[JSONAssert] to verify JSON content, as follows: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- @@ -244,9 +261,11 @@ http://jsonassert.skyscreamer.org[JSONAssert] to verify JSON content: .expectBody() .json("{\"name\":\"Jane\"}") ---- +==== -You can also use https://github.com/jayway/JsonPath[JSONPath] expressions: +You can also use https://github.com/jayway/JsonPath[JSONPath] expressions, as follows: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- @@ -257,15 +276,18 @@ You can also use https://github.com/jayway/JsonPath[JSONPath] expressions: .jsonPath("$[0].name").isEqualTo("Jane") .jsonPath("$[1].name").isEqualTo("Jason"); ---- +==== + [[webtestclient-stream]] -=== Streaming responses +=== Streaming Responses -To test infinite streams (e.g. `"text/event-stream"`, `"application/stream+json"`), -you'll need to exit the chained API, via `returnResult`, immediately after response status -and header assertions, as shown below: +To test infinite streams (for example, `"text/event-stream"` or `"application/stream+json"`), +you need to exit the chained API (by using `returnResult`), immediately after the response status +and header assertions, as the following example shows: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- @@ -276,11 +298,13 @@ and header assertions, as shown below: .returnResult(MyEvent.class); ---- +==== Now you can consume the `Flux`, assert decoded objects as they come, and then -cancel at some point when test objects are met. We recommend using the `StepVerifier` -from the `reactor-test` module to do that, for example: +cancel at some point when test objectives are met. We recommend using the `StepVerifier` +from the `reactor-test` module to do that, as the following example shows: +==== [source,java,intent=0] [subs="verbatim,quotes"] ---- @@ -293,13 +317,15 @@ from the `reactor-test` module to do that, for example: .thenCancel() .verify(); ---- +==== + [[webtestclient-request-body]] -=== Request body +=== Request Body -When it comes to building requests, the `WebTestClient` offers an identical API as the -`WebClient` and the implementation is mostly a simple pass-through. Please refer -to the <> for examples on -how to prepare a request with a body including submitting form data, multipart requests, +When it comes to building requests, the `WebTestClient` offers an API identical to the +`WebClient`, and the implementation is mostly a simple pass-through. See +the <> for examples on +how to prepare a request with a body, including submitting form data, multipart requests, and more. diff --git a/src/docs/asciidoc/testing.adoc b/src/docs/asciidoc/testing.adoc index a94b0dbf2f..4a2582ec98 100644 --- a/src/docs/asciidoc/testing.adoc +++ b/src/docs/asciidoc/testing.adoc @@ -8,15 +8,12 @@ :tabsize: 4 :docinfo1: -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 +This chapter covers Spring's support for integration testing and best practices for unit +testing. The Spring team advocates test-driven development (TDD). +The Spring team has found that the correct use of inversion of control (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. - +set up service locator registries and similar structures). @@ -24,50 +21,58 @@ testing will hopefully convince you of this as well. == 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 <> and on the benefits -of the Spring Framework's support for <>. __(A +the value added by the IoC principle to <> and on the benefits +of the Spring Framework's support for <>. (A thorough treatment of testing in the enterprise is beyond the scope of this reference -manual.)__ - +manual.) [[unit-testing]] == Unit Testing -Dependency Injection should make your code less dependent on the container than it would +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 <> (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 +clean layering and componentization of your codebase 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 +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 +to set up. Emphasizing true unit tests as part of your development methodology can 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. +scenarios, however, the Spring Framework provides mock objects and testing +support classes, which are described in this chapter. [[mock-objects]] === Mock Objects +Spring includes a number of packages dedicated to mocking: + +* <> +* <> +* <> +* <> + + [[mock-objects-env]] ==== Environment The `org.springframework.mock.env` package contains mock implementations of the `Environment` and `PropertySource` abstractions (see -<> -and <>). +<> +and <>). `MockEnvironment` and `MockPropertySource` are useful for developing -__out-of-container__ tests for code that depends on environment-specific properties. +out-of-container tests for code that depends on environment-specific properties. + [[mock-objects-jndi]] @@ -75,50 +80,49 @@ __out-of-container__ tests for code that depends on environment-specific propert 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 +applications. If, for example, JDBC `DataSource` instances get bound to the same JNDI names in +test code as they do in 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 that are useful for testing web contexts, controllers, and filters. These mock objects are targeted at usage with Spring's Web MVC framework and are generally more -convenient to use than dynamic mock objects such as http://www.easymock.org[EasyMock] or -alternative Servlet API mock objects such as http://www.mockobjects.com[MockObjects]. +convenient to use than dynamic mock objects (such as http://www.easymock.org[EasyMock]) or +alternative Servlet API mock objects (such as http://www.mockobjects.com[MockObjects]). -[TIP] -==== -Since Spring Framework 5.0, the mock objects in `org.springframework.mock.web` are based +TIP: Since Spring Framework 5.0, the mock objects in `org.springframework.mock.web` are based on the Servlet 4.0 API. -==== The Spring MVC Test framework builds on the mock Servlet API objects to provide an integration testing framework for Spring MVC. See -<>. +<>. + [[mock-objects-web-reactive]] ==== Spring Web Reactive -The package `org.springframework.mock.http.server.reactive` contains mock +The `org.springframework.mock.http.server.reactive` package contains mock implementations of `ServerHttpRequest` and `ServerHttpResponse` for use in WebFlux -applications. The package `org.springframework.mock.web.server` +applications. The `org.springframework.mock.web.server` package contains a mock `ServerWebExchange` that depends on those mock request and response objects. Both `MockServerHttpRequest` and `MockServerHttpResponse` extend from the same -abstract base classes as server-specific implementations do and share behavior with them. -For example a mock request is immutable once created but you can use the `mutate()` method +abstract base classes as server-specific implementations and share behavior with them. +For example, a mock request is immutable once created, but you can use the `mutate()` method from `ServerHttpRequest` to create a modified instance. In order for the mock response to properly implement the write contract and return a -write completion handle (i.e. `Mono`), by default it uses a `Flux` with +write completion handle (that is, `Mono`), it by default uses a `Flux` with `cache().then()`, which buffers the data and makes it available for assertions in -tests. Applications can set a custom write function for example to test an infinite -stream. +tests. Applications can set a custom write function (for example, to test an infinite +stream). The <> builds on the mock request and response to provide support for testing WebFlux applications without an HTTP server. The client can also be used for @@ -127,61 +131,76 @@ end-to-end tests with a running server. [[unit-testing-support-classes]] -=== Unit Testing support Classes +=== Unit Testing Support Classes + +Spring includes a number of classes that can help with unit testing. They fall into two +categories: + +* <> +* <> + [[unit-testing-utilities]] -==== General testing utilities +==== General Testing Utilities The `org.springframework.test.util` package contains several general purpose utilities for use in unit and integration testing. -`ReflectionTestUtils` is a collection of reflection-based utility methods. Developers use -these methods in testing scenarios where they need to change the value of a constant, set +`ReflectionTestUtils` is a collection of reflection-based utility methods. You can use +these methods in testing scenarios where you need to change the value of a constant, set a non-`public` field, invoke a non-`public` setter method, or invoke a non-`public` -_configuration_ or _lifecycle_ callback method when testing application code involving -use cases such as the following. +configuration or lifecycle callback method when testing application code for +use cases such as the following: -* ORM frameworks such as JPA and Hibernate that condone `private` or `protected` field +* 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 +* Spring's support for annotations (such as `@Autowired`, `@Inject`, and `@Resource`), + that provide dependency injection for `private` or `protected` fields, setter methods, and configuration methods. * Use of annotations such as `@PostConstruct` and `@PreDestroy` for lifecycle callback methods. -`AopTestUtils` is a collection of AOP-related utility methods. These methods can be used +{api-spring-framework}/test/util/AopTestUtils.html[`AopTestUtils`] is a collection of AOP-related utility methods. You can use these methods to obtain a reference to the underlying target object hidden behind one or more Spring -proxies. For example, if you have configured a bean as a dynamic mock using a library -like EasyMock or Mockito and the mock is wrapped in a Spring proxy, you may need direct -access to the underlying mock in order to configure expectations on it and perform -verifications. For Spring's core AOP utilities, see `AopUtils` and `AopProxyUtils`. +proxies. For example, if you have configured a bean as a dynamic mock by using a library +such as EasyMock or Mockito, and the mock is wrapped in a Spring proxy, you may need direct +access to the underlying mock to configure expectations on it and perform +verifications. For Spring's core AOP utilities, see {api-spring-framework}/aop/support/AopUtils.html[`AopUtils`] and {api-spring-framework}/aop/framework/AopProxyUtils.html[`AopProxyUtils`]. + [[unit-testing-spring-mvc]] -==== Spring MVC +==== Spring MVC Testing Utilities -The `org.springframework.test.web` package contains `ModelAndViewAssert`, which you can +The `org.springframework.test.web` package contains {api-spring-framework}/test/web/ModelAndViewAssert.html[`ModelAndViewAssert`], which you can use in combination with JUnit, TestNG, or any other testing framework for unit tests -dealing with Spring MVC `ModelAndView` objects. +that deal with Spring MVC `ModelAndView` objects. .Unit testing Spring MVC Controllers -[TIP] -==== -To unit test your Spring MVC ``Controller``s as POJOs, use `ModelAndViewAssert` combined +TIP: To unit test your Spring MVC `Controller` classes as POJOs, use `ModelAndViewAssert` combined with `MockHttpServletRequest`, `MockHttpSession`, and so on from Spring's <>. For thorough integration testing of your -Spring MVC and REST ``Controller``s in conjunction with your `WebApplicationContext` -configuration for Spring MVC, use the <> instead. -==== - +Spring MVC and REST `Controller` classes in conjunction with your `WebApplicationContext` +configuration for Spring MVC, use the <> instead. [[integration-testing]] == Integration Testing +This section covers (most of the rest of this chapter) covers integration testing for +Spring applications. It includes the following topics: + +* <> +* <> +* <> +* <> +* <> +* <> +* <> + [[integration-testing-overview]] @@ -189,11 +208,11 @@ Framework_>> instead. 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: +Doing so lets you 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. +* Data access using JDBC or an ORM tool. This can include such things as the + correctness of SQL statements, Hibernate queries, JPA entity mappings, and so forth. 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 @@ -207,8 +226,8 @@ 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 <>. 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. +TestContext framework is agnostic of the actual testing framework in use, which allows +instrumentation of tests in various environments, including JUnit, TestNG, and others. @@ -218,7 +237,7 @@ instrumentation of tests in various environments including JUnit, TestNG, and so Spring's integration testing support has the following primary goals: * To manage <> between test - execution. + runs. * To provide <>. * To provide <> appropriate to integration testing. * To supply <> that assist @@ -228,11 +247,12 @@ The next few sections describe each goal and provide links to implementation and configuration details. + [[testing-ctx-management]] -==== Context management and caching +==== Context Management and Caching The Spring TestContext Framework provides consistent loading of Spring -``ApplicationContext``s and ``WebApplicationContext``s as well as caching of those +`ApplicationContext` instances and `WebApplicationContext` instances 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 @@ -240,19 +260,19 @@ project with 50 to 100 Hibernate mapping files might take 10 to 20 seconds to lo 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 or Groovy -configuration metadata -- often in the classpath -- or an array of __annotated classes__ +Test classes typically declare either an array of resource locations for XML or Groovy +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 configuration files for production deployments. 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 +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 +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 <> and <> with the @@ -260,69 +280,71 @@ TestContext framework. [[testing-fixture-di]] -==== Dependency Injection of test fixtures +==== 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 +configure instances of your test classes by using Dependency Injection. This provides a +convenient mechanism for setting up test fixtures by 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 +across various testing scenarios (for example, for configuring Spring-managed object graphs, +transactional proxies, `DataSource` instances, and others), 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`, +As an example, consider a 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 +* 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 +* 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 +* The logic of the `HibernateTitleRepository`: Does the configured instance of this class perform as anticipated? See dependency injection of test fixtures with the <>. + [[testing-tx]] -==== Transaction management +==== 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 +the persistence store. Even when you use 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. +persistent data -- cannot be performed (or verified) outside of 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 +The TestContext framework addresses this issue. By default, the framework creates +and rolls back a transaction for each test. You can 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 +they 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 +the transaction managed for the test, the transaction rolls back by default, and the +database returns to its state prior to execution of the test. Transactional support +is provided to a test by using 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 +If you want a transaction to commit (unusual, but occasionally useful when you want a +particular test to populate or modify the database), you can tell the TestContext framework +to cause the transaction to commit instead of roll back by using the <> annotation. See transaction management with the <>. + [[testing-support-classes]] -==== Support classes for integration testing +==== 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: +which let you 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 +* A `JdbcTemplate`, for executing SQL statements to query the database. You can use such queries + to confirm database state both before 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 <>. @@ -338,166 +360,234 @@ See support classes for the < === 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 +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 +* `countRowsInTable(..)`: Counts the number of rows in the given table. +* `countRowsInTableWhere(..)`: Counts the number of rows in the given table by using +the provided `WHERE` clause. +* `deleteFromTables(..)`: Deletes all rows from the specified tables. +* `deleteFromTableWhere(..)`: Deletes rows from the given table by using the provided +`WHERE` clause. +* `dropTables(..)`: Drops the specified tables. -__Note that <> and -<> -provide convenience methods which delegate to the aforementioned methods in -`JdbcTestUtils`.__ +<> +provide convenience methods that 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 <> -and <>. +database, which you can use in integration tests that interact with a database. For +details, see <> +and <>. +==== [[integration-testing-annotations]] === Annotations +This section covers annotations that you can use when you test Spring applications. It +includes the following topics: + +* <> +* <> +* <> +* <> +* <> + [[integration-testing-annotations-spring]] ==== Spring Testing Annotations -The Spring Framework provides the following set of __Spring-specific__ annotations that +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. +framework. See the corresponding Javadoc for further information, including +default attribute values, attribute aliases, and other details. -===== @BootstrapWith +Spring's testing annotations include the following: -`@BootstrapWith` is a class-level annotation that is used to configure how the _Spring -TestContext Framework_ is bootstrapped. Specifically, `@BootstrapWith` is used to specify -a custom `TestContextBootstrapper`. Consult the <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> + + + +[[spring-testing-annotation-bootstrapwith]] +===== `@BootstrapWith` + +`@BootstrapWith` is a class-level annotation that you can use to configure how the Spring +TestContext Framework is bootstrapped. Specifically, you can use `@BootstrapWith` to specify +a custom `TestContextBootstrapper`. See the <> section for further details. -===== @ContextConfiguration + + +[[spring-testing-annotation-contextconfiguration]] +===== `@ContextConfiguration` `@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. +annotated `classes` used to load the context. Resource locations are typically XML configuration files or Groovy scripts located in -the classpath; whereas, annotated classes are typically `@Configuration` classes. However, +the classpath, while annotated classes are typically `@Configuration` classes. However, resource locations can also refer to files and scripts in the file system, and annotated -classes can be component classes, etc. +classes can be component classes, and so on. +The following example shows a `@ContextConfiguration` annotation that refers to an XML +file: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@ContextConfiguration**("/test-config.xml") + @ContextConfiguration("/test-config.xml") <1> public class XmlApplicationContextTests { // class body... } ---- +<1> Referring to a XML file. +==== +The following example shows a `@ContextConfiguration` annotation that refers to a class: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@ContextConfiguration**(**classes** = TestConfig.class) + @ContextConfiguration(classes = TestConfig.class) <1> public class ConfigClassApplicationContextTests { // class body... } ---- +<1> Referring to a class. +==== As an alternative or in addition to declaring resource locations or annotated classes, -`@ContextConfiguration` may be used to declare `ApplicationContextInitializer` classes. +you can use `@ContextConfiguration` to declare `ApplicationContextInitializer` classes. +The following example shows such a case: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@ContextConfiguration**(**initializers** = CustomContextIntializer.class) + @ContextConfiguration(initializers = CustomContextIntializer.class) <1> public class ContextInitializerTests { // class body... } ---- +<1> Declaring an initializer class. +==== -`@ContextConfiguration` may optionally be used to declare the `ContextLoader` strategy +You can optionally use `@ContextConfiguration` 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`. +loader, since the default loader supports resource `locations`, annotated +`classes`, and `initializers`. +The following example uses both a location and a class: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@ContextConfiguration**(**locations** = "/test-context.xml", **loader** = CustomContextLoader.class) + @ContextConfiguration(locations = "/test-context.xml", loader = CustomContextLoader.class) <1> public class CustomLoaderXmlApplicationContextTests { // class body... } ---- +<1> Configuring both a location and a custom loader. +==== -[NOTE] -==== -`@ContextConfiguration` provides support for __inheriting__ resource locations or -configuration classes as well as context initializers declared by superclasses by -default. -==== +NOTE: `@ContextConfiguration` provides support for inheriting resource locations or +configuration classes as well as context initializers that are, by default, declared by superclasses. See <> and the `@ContextConfiguration` javadocs for further details. -===== @WebAppConfiguration -`@WebAppConfiguration` is a class-level annotation that is used to declare that the + +[[spring-testing-annotation-webappconfiguration]] +===== `@WebAppConfiguration` + +`@WebAppConfiguration` is a class-level annotation that you can use 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` is loaded for the test, using the default value of +`"file:src/main/webapp"` for the path to the root of the web application (that is, 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`. +The following example shows how to use the `@WebAppConfiguration` annotation: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @ContextConfiguration - **@WebAppConfiguration** + @WebAppConfiguration <1> public class WebAppTests { // class body... } ---- +<1> The `@WebAppConfiguration` annotation. +==== -To override the default, specify a different base resource path via the __implicit__ +To override the default, you can specify a different base resource path by using 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. +resource prefix is supplied, the path is assumed to be a file system resource. +The following example shows how to specify a classpath: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @ContextConfiguration - **@WebAppConfiguration("classpath:test-web-resources")** + @WebAppConfiguration("classpath:test-web-resources") <1> public class WebAppTests { // class body... } ---- +<1> Specifying a classpath. +==== 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. +hierarchy. See the {api-spring-framework}/test/context/web/WebAppConfiguration.html[`@WebAppConfiguration` Javadoc] for further details. -===== @ContextHierarchy + + +[[spring-testing-annotation-contexthierarchy]] +===== `@ContextHierarchy` `@ContextHierarchy` is a class-level annotation that is used to define a hierarchy of -``ApplicationContext``s for integration tests. `@ContextHierarchy` should be declared +`ApplicationContext` instances 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. +`@ContextHierarchy` within a single test class (`@ContextHierarchy` can also be +used within a test class hierarchy): +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -522,101 +612,123 @@ used within a test class hierarchy. // 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 -<> and the `@ContextHierarchy` javadocs +<> and the {api-spring-framework}/test/context/ContextHierarchy.html[`@ContextHierarchy` Javadoc] for further examples. -===== @ActiveProfiles -`@ActiveProfiles` is a class-level annotation that is used to declare which __bean -definition profiles__ should be active when loading an `ApplicationContext` for an + +[[spring-testing-annotation-activeprofiles]] +===== `@ActiveProfiles` + +`@ActiveProfiles` is a class-level annotation that is used to declare which bean +definition profiles should be active when loading an `ApplicationContext` for an integration test. +The following example indicates that the `dev` profile should be active: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @ContextConfiguration - **@ActiveProfiles**("dev") + @ActiveProfiles("dev") <1> public class DeveloperTests { // class body... } ---- +<1> Indicate that the `dev` profile should be active. +==== +The following example indicates that both the `dev` and the `integration` profiles should +be active: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @ContextConfiguration - **@ActiveProfiles**({"dev", "integration"}) + @ActiveProfiles({"dev", "integration"}) <1> public class DeveloperIntegrationTests { // class body... } ---- - -[NOTE] +<1> Indicate that the `dev` and `integration` profiles should be active. ==== -`@ActiveProfiles` provides support for __inheriting__ active bean definition profiles -declared by superclasses by default. It is also possible to resolve active bean + +NOTE: `@ActiveProfiles` provides support for inheriting active bean definition profiles +declared by superclasses by default. You can also resolve active bean definition profiles programmatically by implementing a custom <> -and registering it via the `resolver` attribute of `@ActiveProfiles`. -==== +and registering it by using the `resolver` attribute of `@ActiveProfiles`. -See <> and the `@ActiveProfiles` javadocs +See <> and the {api-spring-framework}/test/context/ActiveProfiles.html[`@ActiveProfiles` Javadoc] for examples and further details. -===== @TestPropertySource +[[spring-testing-annotation-testpropertysource]] +===== `@TestPropertySource` -`@TestPropertySource` is a class-level annotation that is used to configure the locations +`@TestPropertySource` is a class-level annotation that you can use to configure the locations of properties files and inlined properties to be added to the set of `PropertySources` in the `Environment` 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 +application declaratively through `@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. +The following example demonstrates how to declare a properties file from the classpath: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @ContextConfiguration - **@TestPropertySource**("/test.properties") + @TestPropertySource("/test.properties") <1> public class MyIntegrationTests { // class body... } ---- +<1> Get properties from `test.properties`. +==== -The following example demonstrates how to declare _inlined_ properties. +The following example demonstrates how to declare inlined properties: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @ContextConfiguration - **@TestPropertySource**(properties = { "timezone = GMT", "port: 4242" }) + @TestPropertySource(properties = { "timezone = GMT", "port: 4242" }) <1> public class MyIntegrationTests { // class body... } ---- +<1> Declare `timezone` and `port` properties. +==== -===== @DirtiesContext + + +[[spring-testing-annotation-dirtiescontext]] +===== `@DirtiesContext` `@DirtiesContext` indicates that the underlying Spring `ApplicationContext` has been -__dirtied__ during the execution of a test (i.e., modified or corrupted in some manner -- +dirtied during the execution of a test (that is, the test modified or corrupted it in some manner -- for example, by changing the state of a singleton bean) and should be closed. 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 +application context is marked as dirty, it is removed from the testing framework's cache +and closed. As a consequence, the underlying Spring container is 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 +You can use `@DirtiesContext` as both a class-level and a method-level annotation within the same class or class hierarchy. In such scenarios, the `ApplicationContext` is marked -as __dirty__ before or after any such annotated method as well as before or after the +as dirty before or after any such annotated method as well as before or after the current test class, depending on the configured `methodMode` and `classMode`. The following examples explain when the context would be dirtied for various @@ -624,110 +736,107 @@ configuration scenarios: * Before the current test class, when declared on a class with class mode set to `BEFORE_CLASS`. - + - +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@DirtiesContext(classMode = BEFORE_CLASS)** + @DirtiesContext(classMode = BEFORE_CLASS) <1> public class FreshContextTests { // some tests that require a new Spring container } ---- - -+ +<1> Dirty the context before the current class. +==== * 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** + @DirtiesContext public class ContextDirtyingTests { // some tests that result in the Spring container being dirtied } ---- - -+ +<1> Dirty the context after the current class. +==== * Before each test method in the current test class, when declared on a class with class mode set to `BEFORE_EACH_TEST_METHOD.` - + - +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@DirtiesContext(classMode = BEFORE_EACH_TEST_METHOD)** + @DirtiesContext(classMode = BEFORE_EACH_TEST_METHOD) <1> public class FreshContextTests { // some tests that require a new Spring container } ---- - -+ +<1> Dirty the context before each test method. +==== * 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 = AFTER_EACH_TEST_METHOD)** + @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) <1> public class ContextDirtyingTests { // some tests that result in the Spring container being dirtied } ---- - -+ +<1> Dirty the context after each test method. +==== * Before the current test, when declared on a method with the method mode set to `BEFORE_METHOD`. - + - +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@DirtiesContext(methodMode = BEFORE_METHOD)** + @DirtiesContext(methodMode = BEFORE_METHOD) <1> @Test public void testProcessWhichRequiresFreshAppCtx() { // some logic that requires a new Spring container } ---- - -+ +<1> Dirty the context before a method. +==== * After the current test, when declared on a method with the method mode set to `AFTER_METHOD` (i.e., the default method mode). - + - +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@DirtiesContext** + @DirtiesContext <1> @Test public void testProcessWhichDirtiesAppCtx() { // some logic that results in the Spring container being dirtied } ---- +<1> Dirty the context after a method. +==== -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. +If you use `@DirtiesContext` in a test whose context is configured as part of a context +hierarchy with `@ContextHierarchy`, you can use the `hierarchyMode` flag to control how +the context cache is cleared. By default, an exhaustive algorithm is used to +clear 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` instances that reside in a sub-hierarchy of the common ancestor context +are removed from the context cache and closed. If the exhaustive algorithm is +overkill for a particular use case, you can specify the simpler current level algorithm, +as the following example shows. +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -742,60 +851,81 @@ specified instead, as seen below. public class ExtendedTests extends BaseTests { @Test - @DirtiesContext(**hierarchyMode = CURRENT_LEVEL**) + @DirtiesContext(hierarchyMode = CURRENT_LEVEL) <1> public void test() { // some logic that results in the child context being dirtied } } ---- +<1> Use the current-level algorithm. +==== -For further details regarding the `EXHAUSTIVE` and `CURRENT_LEVEL` algorithms see the -`DirtiesContext.HierarchyMode` javadocs. +For further details regarding the `EXHAUSTIVE` and `CURRENT_LEVEL` algorithms, see the +{api-spring-framework}/test/annotation/DirtiesContext.HierarchyMode.html[`DirtiesContext.HierarchyMode` Javadoc]. -===== @TestExecutionListeners + + +[[spring-testing-annotation-testexecutionlisteners]] +===== `@TestExecutionListeners` `@TestExecutionListeners` defines class-level metadata for configuring the `TestExecutionListener` implementations that should be registered with the `TestContextManager`. Typically, `@TestExecutionListeners` is used in conjunction with `@ContextConfiguration`. +The following example shows how to define two `TestExecutionListener` implementations: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @ContextConfiguration - **@TestExecutionListeners**({CustomTestExecutionListener.class, AnotherTestExecutionListener.class}) + @TestExecutionListeners({CustomTestExecutionListener.class, AnotherTestExecutionListener.class}) <1> public class CustomTestExecutionListenerTests { // class body... } ---- +<1> Define two `TestExecutionListener` implementations. +==== -`@TestExecutionListeners` supports _inherited_ listeners by default. See the javadocs +By default, `@TestExecutionListeners` supports inherited listeners. See the {api-spring-framework}/test/context/TestExecutionListeners.html[Javadoc] for an example and further details. -===== @Commit + + +[[spring-testing-annotation-commit]] +===== `@Commit` `@Commit` indicates that the transaction for a transactional test method should be -__committed__ after the test method has completed. `@Commit` can be used as a direct -replacement for `@Rollback(false)` in order to more explicitly convey the intent of the -code. Analogous to `@Rollback`, `@Commit` may also be declared as a class-level or +committed after the test method has completed. You can use `@Commit` as a direct +replacement for `@Rollback(false)` to more explicitly convey the intent of the +code. Analogous to `@Rollback`, `@Commit` can also be declared as a class-level or method-level annotation. +The following example shows how to use the `@Commit` annotation: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@Commit** + @Commit <1> @Test public void testProcessWithoutRollback() { // ... } ---- +<1> Commit the result of the test to the database. +==== -===== @Rollback + + +[[spring-testing-annotation-rollback]] +===== `@Rollback` `@Rollback` indicates whether the transaction for a transactional test method should be -__rolled back__ after the test method has completed. If `true`, the transaction is rolled -back; otherwise, the transaction is committed (see also `@Commit`). Rollback semantics -for integration tests in the Spring TestContext Framework default to `true` even if +rolled back after the test method has completed. If `true`, the transaction is rolled +back. Otherwise, the transaction is committed (see also <>). Rollback +for integration tests in the Spring TestContext Framework defaults to `true` even if `@Rollback` is not explicitly declared. When declared as a class-level annotation, `@Rollback` defines the default rollback @@ -803,98 +933,133 @@ semantics for all test methods within the test class hierarchy. When declared as method-level annotation, `@Rollback` defines rollback semantics for the specific test method, potentially overriding class-level `@Rollback` or `@Commit` semantics. +The following example causes a test method's result to not be rolled back (that is, the +result is committed to the database): + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@Rollback**(false) + @Rollback(false) <1> @Test public void testProcessWithoutRollback() { // ... } ---- +<1> Do not roll back the result +==== -===== @BeforeTransaction -`@BeforeTransaction` indicates that the annotated `void` method should be executed -__before__ a transaction is started for test methods configured to run within a -transaction via Spring's `@Transactional` annotation. As of Spring Framework 4.3, + +[[spring-testing-annotation-beforetransaction]] +===== `@BeforeTransaction` + +`@BeforeTransaction` indicates that the annotated `void` method should be run +before a transaction is started, for test methods that have been configured to run within a +transaction by using Spring's `@Transactional` annotation. As of Spring Framework 4.3, `@BeforeTransaction` methods are not required to be `public` and may be declared on Java -8 based interface default methods. +8-based interface default methods. +The following example shows how to use the `@BeforeTransaction` annotation: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@BeforeTransaction** + @BeforeTransaction <1> void beforeTransaction() { // logic to be executed before a transaction is started } ---- +<1> Run this method before a transaction. +==== -===== @AfterTransaction +[[spring-testing-annotation-aftertransaction]] +===== `@AfterTransaction` -`@AfterTransaction` indicates that the annotated `void` method should be executed -__after__ a transaction is ended for test methods configured to run within a transaction -via Spring's `@Transactional` annotation. As of Spring Framework 4.3, `@AfterTransaction` -methods are not required to be `public` and may be declared on Java 8 based interface +`@AfterTransaction` indicates that the annotated `void` method should be run +after a transaction is ended, for test methods that have been configured to run within a transaction +by using Spring's `@Transactional` annotation. As of Spring Framework 4.3, `@AfterTransaction` +methods are not required to be `public` and may be declared on Java 8-based interface default methods. +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@AfterTransaction** + @AfterTransaction <1> void afterTransaction() { // logic to be executed after a transaction has ended } ---- +<1> Run this method after a transaction. +==== -===== @Sql + + +[[spring-testing-annotation-sql]] +===== `@Sql` `@Sql` is used to annotate a test class or test method to configure SQL scripts to be -executed against a given database during integration tests. +run against a given database during integration tests. The following example shows +how to use it: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @Test - **@Sql**({"/test-schema.sql", "/test-user-data.sql"}) + @Sql({"/test-schema.sql", "/test-user-data.sql"}) <1> public void userTest { // execute code that relies on the test schema and test data } ---- +<1> Run two scripts for this test. +==== See <> for further details. -===== @SqlConfig -`@SqlConfig` defines metadata that is used to determine how to parse and execute SQL -scripts configured via the `@Sql` annotation. +[[spring-testing-annotation-sqlconfig]] +===== `@SqlConfig` + +`@SqlConfig` defines metadata that is used to determine how to parse and run SQL +scripts configured with the `@Sql` annotation. The following example shows how to use it: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @Test @Sql( scripts = "/test-user-data.sql", - config = **@SqlConfig**(commentPrefix = "`", separator = "@@") + config = @SqlConfig(commentPrefix = "`", separator = "@@") <1> ) public void userTest { // execute code that relies on the test data } ---- +<1> Set the comment prefix and the separator in SQL scripts. +==== -===== @SqlGroup + + +[[spring-testing-annotation-sqlgroup]] +===== `@SqlGroup` `@SqlGroup` is a container annotation that aggregates several `@Sql` annotations. -`@SqlGroup` can be used natively, declaring several nested `@Sql` annotations, or it can -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. +You can use `@SqlGroup` natively to declare several nested `@Sql` annotations, or you can +use it in conjunction with Java 8's support for repeatable annotations, where `@Sql` can +be declared several times on the same class or method, implicitly generating this +container annotation. The following example shows how to declare an SQL group: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @Test - **@SqlGroup**({ + @SqlGroup({ <1> @Sql(scripts = "/test-schema.sql", config = @SqlConfig(commentPrefix = "`")), @Sql("/test-user-data.sql") )} @@ -902,6 +1067,9 @@ container annotation. // execute code that uses the test schema and test data } ---- +<1> Declare a group of SQL scripts. +==== + [[integration-testing-annotations-standard]] @@ -913,111 +1081,142 @@ tests and can be used anywhere in the Spring Framework. * `@Autowired` * `@Qualifier` -* `@Resource` (javax.annotation) _if JSR-250 is present_ -* `@ManagedBean` (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_ +* `@Resource` (javax.annotation) if JSR-250 is present +* `@ManagedBean` (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] ==== -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. +In the Spring TestContext Framework, you can use `@PostConstruct` and `@PreDestroy` 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 Jupiter's `@BeforeEach`), and that will apply for every test method +If a method within a test class is annotated with `@PostConstruct`, that method +runs before any before methods of the underlying test framework (for example, methods +annotated with JUnit Jupiter's `@BeforeEach`), and that applies 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 +`@PreDestroy`, that method never runs. Therefore, within a test class, we +recommend that you use test lifecycle callbacks from the underlying test framework instead of `@PostConstruct` and `@PreDestroy`. ==== + [[integration-testing-annotations-junit4]] ==== Spring JUnit 4 Testing Annotations -The following annotations are __only__ supported when used in conjunction with the +The following annotations are supported only when used in conjunction with the <>, <>, or <>. +4 rules>>, or <>: -===== @IfProfileValue +* <> +* <> +* <> +* <> + + + +[[integration-testing-annotations-junit4-ifprofilevalue]] +===== `@IfProfileValue` `@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. Otherwise, the test will be disabled and -effectively _ignored_. +provided `name`, the test is enabled. Otherwise, the test is disabled and, +effectively, ignored. -`@IfProfileValue` can be applied at the class level, the method level, or both. +You can apply `@IfProfileValue` at the class level, the method level, or both. Class-level usage of `@IfProfileValue` takes precedence over method-level usage for any methods within that class or its subclasses. Specifically, a test is enabled if it is -enabled both at the class level _and_ at the method level; the absence of +enabled both at the class level and at the method level. The absence of `@IfProfileValue` means the test is implicitly enabled. This is analogous to the semantics of JUnit 4's `@Ignore` annotation, except that the presence of `@Ignore` always disables a test. +The following example shows a test that has an `@IfProfileValue` annotation: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@IfProfileValue**(**name**="java.vendor", **value**="Oracle Corporation") + @IfProfileValue(name="java.vendor", value="Oracle Corporation") <1> @Test public void testProcessWhichRunsOnlyOnOracleJvm() { // some logic that should run only on Java VMs from Oracle Corporation } ---- +<1> Run this test only when the Java vendor is "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 4 environment. +Alternatively, you can configure `@IfProfileValue` with a list of `values` (with `OR` +semantics) to achieve TestNG-like support for test groups in a JUnit 4 environment. Consider the following example: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@IfProfileValue**(**name**="test-groups", **values**={"unit-tests", "integration-tests"}) + @IfProfileValue(name="test-groups", values={"unit-tests", "integration-tests"}) <1> @Test public void testProcessWhichRunsForUnitOrIntegrationTestGroups() { // some logic that should run only for unit and integration test groups } ---- +<1> Run this test for unit tests and integration tests. +==== -===== @ProfileValueSourceConfiguration + + +[[integration-testing-annotations-junit4-profilevaluesourceconfiguration]] +===== `@ProfileValueSourceConfiguration` `@ProfileValueSourceConfiguration` is a class-level annotation that specifies what type -of `ProfileValueSource` to use when retrieving __profile values__ configured through the +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. +test, `SystemProfileValueSource` is used by default. The following example shows how to +use `@ProfileValueSourceConfiguration`: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@ProfileValueSourceConfiguration**(CustomProfileValueSource.class) + @ProfileValueSourceConfiguration(CustomProfileValueSource.class) <1> public class CustomProfileValueSourceTests { // class body... } ---- +<1> Use a custom profile value source. +==== -===== @Timed + + +[[integration-testing-annotations-junit4-timed]] +===== `@Timed` `@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. +The time period includes running the test method itself, any repetitions of the +test (see `@Repeat`), as well as any setting up or tearing down of the test fixture. +The following example shows how to use it: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@Timed**(millis=1000) + @Timed(millis=1000) <1> public void testProcessWithOneSecondTimeout() { // some logic that should not take longer than 1 second to execute } ---- +<1> Set the time period for the test to one second. +==== Spring's `@Timed` annotation has different semantics than JUnit 4's `@Test(timeout=...)` support. Specifically, due to the manner in which JUnit 4 handles test execution timeouts @@ -1026,120 +1225,167 @@ preemptively fails the test if the test takes too long. Spring's `@Timed`, on th hand, does not preemptively fail the test but rather waits for the test to complete before failing. -===== @Repeat -`@Repeat` indicates that the annotated test method must be executed repeatedly. The + +[[integration-testing-annotations-junit4-repeat]] +===== `@Repeat` + +`@Repeat` indicates that the annotated test method must be run 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. +well as any setting up or tearing down of the test fixture. +The following example shows how to use the `@Repeat` annotation: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@Repeat**(10) + @Repeat(10) <1> @Test public void testProcessRepeatedly() { // ... } ---- +<1> Repeat this test ten times. +==== + [[integration-testing-annotations-junit-jupiter]] ==== Spring JUnit Jupiter Testing Annotations -The following annotations are __only__ supported when used in conjunction with the -<> and JUnit Jupiter (i.e., the -programming model in JUnit 5). +The following annotations are supported only when used in conjunction with the +<> and JUnit Jupiter (that is, the +programming model in JUnit 5): -===== @SpringJUnitConfig +* <> +* <> +* <> +* <> -`@SpringJUnitConfig` is a _composed annotation_ that combines + + +[[integration-testing-annotations-junit-jupiter-springjunitconfig]] +===== `@SpringJUnitConfig` + +`@SpringJUnitConfig` is a composed annotation that combines `@ExtendWith(SpringExtension.class)` from JUnit Jupiter with `@ContextConfiguration` from the Spring TestContext Framework. It can be used at the class level as a drop-in replacement for `@ContextConfiguration`. With regard to configuration options, the only difference between `@ContextConfiguration` and `@SpringJUnitConfig` is that annotated -classes may be declared via the `value` attribute in `@SpringJUnitConfig`. +classes may be declared with the `value` attribute in `@SpringJUnitConfig`. +The following example shows how to use the `@SpringJUnitConfig` annotation to specify a +configuration class: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@SpringJUnitConfig**(TestConfig.class) + @SpringJUnitConfig(TestConfig.class) <1> class ConfigurationClassJUnitJupiterSpringTests { // class body... } ---- +<1> Specify the configuration class. +==== +The following example shows how to use the `@SpringJUnitConfig` annotation to specify a +the location of a configuration file: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@SpringJUnitConfig**(**locations** = "/test-config.xml") + @SpringJUnitConfig(locations = "/test-config.xml") <1> class XmlJUnitJupiterSpringTests { // class body... } ---- +<1> Specify the location of a configuration file. +==== -See <> as well as the javadocs for `@SpringJUnitConfig` and +See <> as well as the {api-spring-framework}/test/context/junit/jupiter/SpringJUnitConfig.html[Javadoc for `@SpringJUnitConfig`] and `@ContextConfiguration` for further details. -===== @SpringJUnitWebConfig -`@SpringJUnitWebConfig` is a _composed annotation_ that combines + +[[integration-testing-annotations-junit-jupiter-springjunitwebconfig]] +===== `@SpringJUnitWebConfig` + +`@SpringJUnitWebConfig` is a composed annotation that combines `@ExtendWith(SpringExtension.class)` from JUnit Jupiter with `@ContextConfiguration` and -`@WebAppConfiguration` from the Spring TestContext Framework. It can be used at the class +`@WebAppConfiguration` from the Spring TestContext Framework. You can use it at the class level as a drop-in replacement for `@ContextConfiguration` and `@WebAppConfiguration`. With regard to configuration options, the only difference between `@ContextConfiguration` -and `@SpringJUnitWebConfig` is that annotated classes may be declared via the `value` -attribute in `@SpringJUnitWebConfig`. In addition, the `value` attribute from -`@WebAppConfiguration` can only be overridden via the `resourcePath` attribute in +and `@SpringJUnitWebConfig` is that you can declare annotated classes bu using the `value` +attribute in `@SpringJUnitWebConfig`. In addition, you can override the `value` attribute from +`@WebAppConfiguration` only by using the `resourcePath` attribute in `@SpringJUnitWebConfig`. +The following example shows how to use the `@SpringJUnitWebConfig` annotation to specify a +configuration class: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@SpringJUnitWebConfig**(TestConfig.class) + @SpringJUnitWebConfig(TestConfig.class) <1> class ConfigurationClassJUnitJupiterSpringWebTests { // class body... } ---- +<1> Specify the configuration class. +==== +The following example shows how to use the `@SpringJUnitWebConfig` annotation to specify a +the location of a configuration file: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@SpringJUnitWebConfig**(**locations** = "/test-config.xml") + @SpringJUnitWebConfig(locations = "/test-config.xml") <1> class XmlJUnitJupiterSpringWebTests { // class body... } ---- +<1>Specify the location of a configuration file. +==== -See <> as well as the javadocs for `@SpringJUnitWebConfig`, -`@ContextConfiguration`, and `@WebAppConfiguration` for further details. +See <> as well as the Javadoc for {api-spring-framework}/test/context/junit/jupiter/web/SpringJUnitWebConfig.html[`@SpringJUnitWebConfig`], +{api-spring-framework}/test/context/ContextConfiguration.html[`@ContextConfiguration`], and {api-spring-framework}/test/context/web/WebAppConfiguration.html[`@WebAppConfiguration`] for further details. -===== @EnabledIf + + +[[integration-testing-annotations-junit-jupiter-enabledif]] +===== `@EnabledIf` `@EnabledIf` is used to signal that the annotated JUnit Jupiter test class or test method -is _enabled_ and should be executed if the supplied `expression` evaluates to `true`. +is enabled and should be run if the supplied `expression` evaluates to `true`. Specifically, if the expression evaluates to `Boolean.TRUE` or a `String` equal to -`"true"` (ignoring case), the test will be __enabled__. When applied at the class level, +`true` (ignoring case), the test is enabled. When applied at the class level, all test methods within that class are automatically enabled by default as well. -Expressions can be any of the following. +Expressions can be any of the following: -* <> (SpEL) expression – for example: - - `@EnabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")` +* <> (SpEL) expression. For example: + `@EnabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")` * Placeholder for a property available in the Spring - <> – for example: - - `@EnabledIf("${smoke.tests.enabled}")` -* Text literal – for example: - - `@EnabledIf("true")` + <>. For example: + `@EnabledIf("${smoke.tests.enabled}")` +* Text literal. For example: + `@EnabledIf("true")` -Note, however, that a text literal which is _not_ the result of dynamic resolution of a -property placeholder is of zero practical value since `@EnabledIf("false")` is equivalent +Note, however, that a text literal that is not the result of dynamic resolution of a +property placeholder is of zero practical value, since `@EnabledIf("false")` is equivalent to `@Disabled` and `@EnabledIf("true")` is logically meaningless. -`@EnabledIf` may be used as a meta-annotation to create custom composed annotations. For -example, a custom `@EnabledOnMac` annotation can be created as follows. +You can use `@EnabledIf` as a meta-annotation to create custom composed annotations. For +example, you can create a custom `@EnabledOnMac` annotation as follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1151,32 +1397,37 @@ example, a custom `@EnabledOnMac` annotation can be created as follows. ) public @interface EnabledOnMac {} ---- +==== -===== @DisabledIf + + +[[integration-testing-annotations-junit-jupiter=-disabledif]] +===== `@DisabledIf` `@DisabledIf` is used to signal that the annotated JUnit Jupiter test class or test -method is _disabled_ and should not be executed if the supplied `expression` evaluates to +method is disabled and should not be executed if the supplied `expression` evaluates to `true`. Specifically, if the expression evaluates to `Boolean.TRUE` or a `String` equal -to `"true"` (ignoring case), the test will be __disabled__. When applied at the class +to `true` (ignoring case), the test is disabled. When applied at the class level, all test methods within that class are automatically disabled as well. -Expressions can be any of the following. +Expressions can be any of the following: -* <> (SpEL) expression – for example: - - `@DisabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")` +* <> (SpEL) expression. For example: + `@DisabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")` * Placeholder for a property available in the Spring - <> – for example: - - `@DisabledIf("${smoke.tests.disabled}")` -* Text literal – for example: - - `@DisabledIf("true")` + <>. For example: + `@DisabledIf("${smoke.tests.disabled}")` +* Text literal. For example: + `@DisabledIf("true")` -Note, however, that a text literal which is _not_ the result of dynamic resolution of a -property placeholder is of zero practical value since `@DisabledIf("true")` is +Note, however, that a text literal that is not the result of dynamic resolution of a +property placeholder is of zero practical value, since `@DisabledIf("true")` is equivalent to `@Disabled` and `@DisabledIf("false")` is logically meaningless. -`@DisabledIf` may be used as a meta-annotation to create custom composed annotations. For -example, a custom `@DisabledOnMac` annotation can be created as follows. +You can use `@DisabledIf` as a meta-annotation to create custom composed annotations. For +example, you can create a custom `@DisabledOnMac` annotation as follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1188,16 +1439,18 @@ example, a custom `@DisabledOnMac` annotation can be created as follows. ) public @interface DisabledOnMac {} ---- +==== + [[integration-testing-annotations-meta]] ==== Meta-Annotation Support for Testing -It is possible to use most test-related annotations as -<> in order to create custom _composed -annotations_ and reduce configuration duplication across a test suite. +You can use most test-related annotations as +<> 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 +You can use each of the following as a meta-annotation in conjunction with the <>. * `@BootstrapWith` @@ -1225,9 +1478,9 @@ Each of the following may be used as meta-annotations in conjunction with the * `@EnabledIf` _(only supported on JUnit Jupiter)_ * `@DisabledIf` _(only supported on JUnit Jupiter)_ -For example, if we discover that we are repeating the following configuration across our -_JUnit 4_ based test suite... +Consider the following example: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1243,10 +1496,13 @@ _JUnit 4_ based test suite... @Transactional public class UserRepositoryTests { } ---- +==== -We can reduce the above duplication by introducing a custom _composed annotation_ that -centralizes the common test configuration for Spring like this: +If we discover that we are repeating the preceding configuration across our +JUnit 4-based test suite, we can reduce the duplication by introducing a custom composed annotation that +centralizes the common test configuration for Spring, as follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1257,10 +1513,12 @@ centralizes the common test configuration for Spring like this: @Transactional public @interface TransactionalDevTestConfig { } ---- +==== Then we can use our custom `@TransactionalDevTestConfig` annotation to simplify the -configuration of individual JUnit 4 based test classes as follows: +configuration of individual JUnit 4 based test classes, as follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1272,12 +1530,13 @@ configuration of individual JUnit 4 based test classes as follows: @TransactionalDevTestConfig public class UserRepositoryTests { } ---- +==== -If we are writing tests using JUnit Jupiter, we can reduce code duplication even further -since annotations in JUnit 5 can also be used as meta-annotations. For example, if we -discover that we are repeating the following configuration across our JUnit Jupiter based -test suite... +If we writ tests that use JUnit Jupiter, we can reduce code duplication even further, +since annotations in JUnit 5 can also be used as meta-annotations. +Consider the following example: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1293,10 +1552,14 @@ test suite... @Transactional class UserRepositoryTests { } ---- +==== -We can reduce the above duplication by introducing a custom _composed annotation_ -that centralizes the common test configuration for Spring and JUnit Jupiter like this: +If we +discover that we are repeating the preceding configuration across our JUnit Jupiter-based +test suite, we can reduce the duplication by introducing a custom composed annotation +that centralizes the common test configuration for Spring and JUnit Jupiter, as follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1308,10 +1571,12 @@ that centralizes the common test configuration for Spring and JUnit Jupiter like @Transactional public @interface TransactionalDevTestConfig { } ---- +==== Then we can use our custom `@TransactionalDevTestConfig` annotation to simplify the -configuration of individual JUnit Jupiter based test classes as follows: +configuration of individual JUnit Jupiter based test classes, as follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1321,14 +1586,16 @@ configuration of individual JUnit Jupiter based test classes as follows: @TransactionalDevTestConfig class UserRepositoryTests { } ---- +==== Since JUnit Jupiter supports the use of `@Test`, `@RepeatedTest`, `ParameterizedTest`, -etc. as meta-annotations, it is also possible to create custom composed annotations at -the test method level. For example, if we wish to create a _composed annotation_ that +and others as meta-annotations, you can also create custom composed annotations at +the test method level. For example, if we wish to create a composed annotation that combines the `@Test` and `@Tag` annotations from JUnit Jupiter with the `@Transactional` -annotation from Spring, we could create an `@TransactionalIntegrationTest` annotation as -follows. +annotation from Spring, we could create an `@TransactionalIntegrationTest` annotation, as +follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1339,10 +1606,12 @@ follows. @Test // org.junit.jupiter.api.Test public @interface TransactionalIntegrationTest { } ---- +==== Then we can use our custom `@TransactionalIntegrationTest` annotation to simplify the -configuration of individual JUnit Jupiter based test methods as follows: +configuration of individual JUnit Jupiter based test methods, as follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1352,8 +1621,9 @@ configuration of individual JUnit Jupiter based test methods as follows: @TransactionalIntegrationTest void deleteOrder() { } ---- +==== -For further details, consult the <>. @@ -1361,69 +1631,74 @@ Annotation Programming Model>>. [[testcontext-framework]] === Spring TestContext Framework -The __Spring TestContext Framework__ (located in the +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 +TestContext framework also places a great deal of importance on convention over +configuration, with reasonable defaults that you can override through annotation-based configuration. In addition to generic testing infrastructure, the TestContext framework provides -explicit support for JUnit 4, JUnit Jupiter (a.k.a., JUnit 5), and TestNG. For JUnit 4 +explicit support for JUnit 4, JUnit Jupiter (AKA JUnit 5), and TestNG. For JUnit 4 and TestNG, Spring provides `abstract` support classes. Furthermore, Spring provides a -custom JUnit `Runner` and custom JUnit `Rules` for _JUnit 4_ as well as a custom -`Extension` for _JUnit Jupiter_ that allow one to write so-called __POJO test classes__. -POJO test classes are not required to extend a particular class hierarchy such as the +custom JUnit `Runner` and custom JUnit `Rules` for JUnit 4 and a custom +`Extension` for JUnit Jupiter that let you write so-called POJO test classes. +POJO test classes are not required to extend a particular class hierarchy, such as the `abstract` support classes. 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 +If you are interested only in using the framework and are not interested in +extending it with your own custom listeners or custom loaders, feel free to go directly to the configuration (<>, <>, <>), <>, and <> sections. + [[testcontext-key-abstractions]] -==== Key abstractions +==== Key Abstractions The core of the framework consists of the `TestContextManager` class and the `TestContext`, `TestExecutionListener`, and `SmartContextLoader` interfaces. A -`TestContextManager` is created per test class (e.g., for the execution of all test -methods within a single test class in JUnit Jupiter). The `TestContextManager` in turn +`TestContextManager` is created for each test class (for example, for the execution of all test +methods within a single test class in JUnit Jupiter). 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` implementations, which instrument the actual test execution by providing dependency injection, managing transactions, and so on. A `SmartContextLoader` is responsible for loading an `ApplicationContext` for a given test -class. Consult the javadocs and the Spring test suite for further information and +class. See the {api-spring-framework}[Javadoc] and the Spring test suite for further information and examples of various implementations. -===== TestContext -`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 + +===== `TestContext` + +`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 `SmartContextLoader` to load an `ApplicationContext` if requested. -===== TestContextManager -`TestContextManager` is the main entry point into the __Spring TestContext Framework__ + +===== `TestContextManager` + +`TestContextManager` is the main entry point into the Spring TestContext Framework and is responsible for managing a single `TestContext` and signaling events to each registered `TestExecutionListener` at well-defined test execution points: -* prior to any __before class__ or __before all__ methods of a particular testing framework -* test instance post-processing -* prior to any __before__ or __before each__ methods of a particular testing framework -* immediately before execution of the test method but after test setup -* immediately after execution of the test method but before test tear down -* after any __after__ or __after each__ methods of a particular testing framework -* after any __after class__ or __after all__ methods of a particular testing framework +* Prior to any "`before class`" or "`before all`" methods of a particular testing framework. +* Test instance post-processing. +* Prior to any "`before`" or "`before each`" methods of a particular testing framework. +* Immediately before execution of the test method but after test setup. +* Immediately after execution of the test method but before test tear down. +* After any "`after`" or "`after each`" methods of a particular testing framework. +* After any "`after class`" or "`after all`" methods of a particular testing framework. -===== TestExecutionListener +===== `TestExecutionListener` -`TestExecutionListener` defines the API for reacting to test execution events published +`TestExecutionListener` defines the API for reacting to test-execution events published by the `TestContextManager` with which the listener is registered. See <>. @@ -1431,137 +1706,143 @@ by the `TestContextManager` with which the listener is registered. See `ContextLoader` is a strategy interface that was 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 +You should implement `SmartContextLoader` instead of this interface to provide support for annotated classes, active bean definition profiles, test property sources, context hierarchies, and `WebApplicationContext` support. `SmartContextLoader` is an 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 +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 +* `DelegatingSmartContextLoader`: One of two default loaders, it delegates internally to an `AnnotationConfigContextLoader`, a `GenericXmlContextLoader`, or a -`GenericGroovyXmlContextLoader` depending either on the configuration declared for the +`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 +Groovy support is enabled only if Groovy is on the classpath. +* `WebDelegatingSmartContextLoader`: One of two default loaders, it delegates internally to an `AnnotationConfigWebContextLoader`, a `GenericXmlWebContextLoader`, or a -`GenericGroovyXmlWebContextLoader` depending either on the configuration declared for the +`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. +web `ContextLoader` is used only if `@WebAppConfiguration` is present on the test +class. Groovy support is enabled only 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. [[testcontext-bootstrapping]] -==== Bootstrapping the TestContext framework +==== Bootstrapping the TestContext Framework The default configuration for the internals of the Spring TestContext Framework is sufficient for all common use cases. However, there are times when a development team or third party framework would like to change the default `ContextLoader`, implement a custom `TestContext` or `ContextCache`, augment the default sets of -`ContextCustomizerFactory` and `TestExecutionListener` implementations, etc. For such low -level control over how the TestContext framework operates, Spring provides a +`ContextCustomizerFactory` and `TestExecutionListener` implementations, and so on. For such +low-level control over how the TestContext framework operates, Spring provides a bootstrapping strategy. -`TestContextBootstrapper` defines the SPI for _bootstrapping_ the TestContext framework. +`TestContextBootstrapper` defines the SPI for bootstrapping the TestContext framework. A `TestContextBootstrapper` is used by the `TestContextManager` to load the `TestExecutionListener` implementations for the current test and to build the -`TestContext` that it manages. A custom bootstrapping strategy can be configured for a -test class (or test class hierarchy) via `@BootstrapWith`, either directly or as a -meta-annotation. If a bootstrapper is not explicitly configured via `@BootstrapWith`, -either the `DefaultTestContextBootstrapper` or the `WebTestContextBootstrapper` will be +`TestContext` that it manages. You can configure a custom bootstrapping strategy for a +test class (or test class hierarchy) by using `@BootstrapWith`, either directly or as a +meta-annotation. If a bootstrapper is not explicitly configured by using `@BootstrapWith`, +either the `DefaultTestContextBootstrapper` or the `WebTestContextBootstrapper` is used, depending on the presence of `@WebAppConfiguration`. -Since the `TestContextBootstrapper` SPI is likely to change in the future in order to -accommodate new requirements, implementers are strongly encouraged not to implement this +Since the `TestContextBootstrapper` SPI is likely to change in the future (to +accommodate new requirements), we strongly encourage implementers not to implement this interface directly but rather to extend `AbstractTestContextBootstrapper` or one of its concrete subclasses instead. + [[testcontext-tel-config]] -==== TestExecutionListener configuration +==== `TestExecutionListener` Configuration Spring provides the following `TestExecutionListener` implementations that are registered -by default, exactly in this order. +by default, exactly in the following order: -* `ServletTestExecutionListener`: configures Servlet API mocks for a - `WebApplicationContext` -* `DirtiesContextBeforeModesTestExecutionListener`: handles the `@DirtiesContext` annotation for - _before_ modes -* `DependencyInjectionTestExecutionListener`: provides dependency injection for the test - instance -* `DirtiesContextTestExecutionListener`: handles the `@DirtiesContext` annotation for - _after_ modes -* `TransactionalTestExecutionListener`: provides transactional test execution with - default rollback semantics -* `SqlScriptsTestExecutionListener`: executes SQL scripts configured via the `@Sql` - annotation +. `ServletTestExecutionListener`: Configures Servlet API mocks for a + `WebApplicationContext`. +. `DirtiesContextBeforeModesTestExecutionListener`: Handles the `@DirtiesContext` annotation for + "`before`" modes. +. `DependencyInjectionTestExecutionListener`: Provides dependency injection for the test + instance. +. `DirtiesContextTestExecutionListener`: Handles the `@DirtiesContext` annotation for + "`after`" modes. +. `TransactionalTestExecutionListener`: Provides transactional test execution with + default rollback semantics. +. `SqlScriptsTestExecutionListener`: Runs SQL scripts configured by using the `@Sql` + annotation. [[testcontext-tel-config-registering-tels]] -===== Registering custom TestExecutionListeners +===== Registering Custom `TestExecutionListener` Implementations + +You can register custom `TestExecutionListener` implementations for a test class and its subclasses +by using the `@TestExecutionListeners` annotation. See +<> and the {}api-spring-framework/test/context/TestExecutionListeners.html[Javadoc for +`@TestExecutionListeners`] for details and examples. + -Custom ``TestExecutionListener``s can be registered for a test class and its subclasses -via the `@TestExecutionListeners` annotation. See -<> and the javadocs for -`@TestExecutionListeners` for details and examples. [[testcontext-tel-config-automatic-discovery]] -===== Automatic discovery of default TestExecutionListeners +===== Automatic Discovery of Default `TestExecutionListener` Implementations -Registering custom ``TestExecutionListener``s via `@TestExecutionListeners` is suitable -for custom listeners that are used in limited testing scenarios; however, it can become +Registering custom `TestExecutionListener` implementations by using `@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. Since Spring -Framework 4.1, this issue is addressed via support for automatic discovery of _default_ -`TestExecutionListener` implementations via the `SpringFactoriesLoader` mechanism. +Framework 4.1, this issue is addressed through support for automatic discovery of default +`TestExecutionListener` implementations through the `SpringFactoriesLoader` mechanism. Specifically, the `spring-test` module declares all core default -``TestExecutionListener``s under the +TestExecutionListener` implementations 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. +contribute their own `TestExecutionListener` implementations to the list of default listeners in the +same manner through their own `META-INF/spring.factories` properties file. + + [[testcontext-tel-config-ordering]] -===== Ordering TestExecutionListeners +===== Ordering `TestExecutionListener` Implementations -When the TestContext framework discovers default ``TestExecutionListener``s via the -aforementioned `SpringFactoriesLoader` mechanism, the instantiated listeners are sorted -using Spring's `AnnotationAwareOrderComparator` which honors Spring's `Ordered` interface +When the TestContext framework discovers default `TestExecutionListener` implementations through the +<> `SpringFactoriesLoader` mechanism, the instantiated listeners are sorted +by 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 +`TestExecutionListener` implementations 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 +default `TestExecutionListener` implementations are registered in the proper order by implementing +`Ordered` or declaring `@Order`. See the Javadoc for the `getOrder()` methods of the +core default `TestExecutionListener` implementations for details on what values are assigned to each core listener. [[testcontext-tel-config-merging]] -===== Merging TestExecutionListeners +===== Merging `TestExecutionListener` Implementations If a custom `TestExecutionListener` is registered via `@TestExecutionListeners`, the -_default_ listeners will not be registered. In most common testing scenarios, this +default listeners are not 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. +any custom listeners. The following listing demonstrates this style of configuration: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1579,33 +1860,35 @@ any custom listeners. The following listing demonstrates this style of configura // 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, and `DirtiesContextBeforeModesTestExecutionListener` was introduced in Spring Framework 4.2. Furthermore, third-party frameworks like Spring -Security register their own default ``TestExecutionListener``s via the aforementioned +Security register their own default `TestExecutionListener` implementations by using the aforementioned <>. -To avoid having to be aware of and re-declare **all** _default_ listeners, the -`mergeMode` attribute of `@TestExecutionListeners` can be set to +To avoid having to be aware of and re-declare all default listeners, you can set the +`mergeMode` attribute of `@TestExecutionListeners` 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 +sorted according to the semantics of `AnnotationAwareOrderComparator`, as described in <>. 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 +with `@Order`, it can influence the position in which it is merged with the defaults. +Otherwise, locally declared listeners are 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. +defaults in front of the `ServletTestExecutionListener`, and the previous example could +be replaced with the following: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1618,26 +1901,29 @@ be replaced with the following. // class body... } ---- +==== + [[testcontext-ctx-management]] -==== Context 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 +for which it is responsible. Test instances do not automatically receive access to the configured `ApplicationContext`. However, if a test class implements the `ApplicationContextAware` interface, a reference to the `ApplicationContext` is supplied to the test instance. Note that `AbstractJUnit4SpringContextTests` and -`AbstractTestNGSpringContextTests` implement `ApplicationContextAware` and therefore +`AbstractTestNGSpringContextTests` implement `ApplicationContextAware` and, therefore, provide access to the `ApplicationContext` automatically. .@Autowired ApplicationContext [TIP] -==== +===== 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: +on either a field or setter method, as the following example shows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1645,21 +1931,24 @@ on either a field or setter method. For example: @ContextConfiguration public class MyTest { - **@Autowired** + @Autowired <1> private ApplicationContext applicationContext; // class body... } ---- +<1> Autowiring a field. +==== Similarly, if your test is configured to load a `WebApplicationContext`, you can inject -the web application context into your test as follows: +the web application context into your test, as follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @RunWith(SpringRunner.class) - **@WebAppConfiguration** + @WebAppConfiguration <1> @ContextConfiguration public class MyWebAppTest { **@Autowired** @@ -1668,74 +1957,97 @@ the web application context into your test as follows: // class body... } ---- - -Dependency injection via `@Autowired` is provided by the -`DependencyInjectionTestExecutionListener` which is configured by default (see -<>). +<1> Injecting the `WebApplicationContext`. ==== +Dependency injection by using `@Autowired` is provided by the +`DependencyInjectionTestExecutionListener`, which is configured by default (see +<>). +===== + 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 +configuration is achieved 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 +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`. +addition to context resource locations and annotated classes, an application context +can also be configured through application context initializers. -The following sections explain how to configure an `ApplicationContext` via XML +The following sections explain how to configure an `ApplicationContext` by using XML configuration files, Groovy scripts, annotated classes (typically `@Configuration` -classes), or context initializers using Spring's `@ContextConfiguration` annotation. +classes), or context initializers that use 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 + + +[[testcontext-ctx-management-xml]] +===== Context Configuration with XML resources + +To load an `ApplicationContext` for your tests by 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 +relative path (for example, `context.xml`) is 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__. +a slash is treated as an absolute classpath location (for example, +`/org/example/config.xml`). A path that represents a resource URL (i.e., a path +prefixed with `classpath:`, `file:`, `http:`, etc.) is used _as is_. +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @RunWith(SpringRunner.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"})** + @ContextConfiguration(locations={"/app-config.xml", "/test-config.xml"}) <1> public class MyTest { // class body... } ---- +<1> Setting the locations attribute to a list of XML files. +==== `@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. +demonstrated in the following example: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @RunWith(SpringRunner.class) - **@ContextConfiguration({"/app-config.xml", "/test-config.xml"})** + @ContextConfiguration({"/app-config.xml", "/test-config.xml"}) <1> public class MyTest { // class body... } ---- +<1> Specifying XML files without using the `location` attribute. +==== -If you omit both the `locations` and `value` attributes from the `@ContextConfiguration` -annotation, the TestContext framework will attempt to detect a default XML resource +If you omit both the `locations` and the `value` attributes from the `@ContextConfiguration` +annotation, the TestContext framework tries 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"`. +`"classpath:com/example/MyTest-context.xml"`. The following example shows how to do so: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1744,49 +2056,56 @@ a default location based on the name of the test class. If your class is named @RunWith(SpringRunner.class) // ApplicationContext will be loaded from // "classpath:com/example/MyTest-context.xml" - **@ContextConfiguration** + @ContextConfiguration <1> public class MyTest { // class body... } ---- +<1> Loading configuration from the default location. +==== + + [[testcontext-ctx-management-groovy]] -===== Context configuration with Groovy scripts +===== Context Configuration with Groovy Scripts -To load an `ApplicationContext` for your tests using Groovy scripts that utilize the -<>, annotate your test class with +To load an `ApplicationContext` for your tests by using Groovy scripts that use the +<>, you can 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 <>. - .Enabling Groovy script support -[TIP] -==== -Support for using Groovy scripts to load an `ApplicationContext` in the Spring +TIP: Support for using Groovy scripts to load an `ApplicationContext` in the Spring TestContext Framework is enabled automatically if Groovy is on the classpath. -==== +The following example shows how to specify Groovy configuration files: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @RunWith(SpringRunner.class) // ApplicationContext will be loaded from "/AppConfig.groovy" and // "/TestConfig.groovy" in the root of the classpath - **@ContextConfiguration({"/AppConfig.groovy", "/TestConfig.Groovy"})** + @ContextConfiguration({"/AppConfig.groovy", "/TestConfig.Groovy"}) <1> public class MyTest { // class body... } ---- +<1> Specifying the location of Groovy configuration files. +==== If you omit both the `locations` and `value` attributes from the `@ContextConfiguration` -annotation, the TestContext framework will attempt to detect a default Groovy script. +annotation, the TestContext framework tries 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"`. +`com.example.MyTest`, the Groovy context loader loads your application context from +`"classpath:com/example/MyTestContext.groovy"`. The following example shows how to use +the default: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1795,22 +2114,25 @@ detect a default location based on the name of the test class. If your class is @RunWith(SpringRunner.class) // ApplicationContext will be loaded from // "classpath:com/example/MyTestContext.groovy" - **@ContextConfiguration** + @ContextConfiguration <1> public class MyTest { // class body... } ---- - -.Declaring XML config and Groovy scripts simultaneously -[TIP] +<1> Loading configuration from the default location. ==== -Both XML configuration files and Groovy scripts can be declared simultaneously via the + +.Declaring XML configuration and Groovy scripts simultaneously +[TIP] +===== +You can declare both XML configuration files and Groovy scripts simultaneously by using 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`. +resource location ends with `.xml`, it is loaded by using an `XmlBeanDefinitionReader`. +Otherwise, it is loaded by using a `GroovyBeanDefinitionReader`. -The following listing demonstrates how to combine both in an integration test. +The following listing shows how to combine both in an integration test: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -1823,59 +2145,67 @@ The following listing demonstrates how to combine both in an integration test. } ---- ==== +===== + + [[testcontext-ctx-management-javaconfig]] -===== Context configuration with annotated classes +===== Context Configuration with Annotated Classes -To load an `ApplicationContext` for your tests using __annotated classes__ (see +To load an `ApplicationContext` for your tests by using annotated classes (see <>), -annotate your test class with `@ContextConfiguration` and configure the +you can annotate your test class with `@ContextConfiguration` and configure the `classes` attribute with an array that contains references to annotated classes. +The following example shows how to do so: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @RunWith(SpringRunner.class) // ApplicationContext will be loaded from AppConfig and TestConfig - **@ContextConfiguration(classes = {AppConfig.class, TestConfig.class})** + @ContextConfiguration(classes = {AppConfig.class, TestConfig.class}) <1> public class MyTest { // class body... } ---- +<1> Specifying annotated classes. +==== .Annotated Classes [TIP] ==== -The term __annotated class__ can refer to any of the following. +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 +* A class annotated with `@Configuration`. +* A component (that, a class annotated with `@Component`, `@Service`, `@Repository`, and others). +* 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__. +See the Javadoc of {api-spring-framework}/context/annotation/Configuration.html[`@Configuration`] and {api-spring-framework}/context/annotation/Bean.html[`@Bean`] for further information regarding +the configuration and semantics of annotated classes, paying special attention to +the discussion of `@Bean` Lite Mode. ==== If you omit the `classes` attribute from the `@ContextConfiguration` annotation, the -TestContext framework will attempt to detect the presence of default configuration +TestContext framework tries 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 +`AnnotationConfigWebContextLoader` detect all `static` nested classes of the test class +that meet the requirements for configuration class implementations, as specified in the +{api-spring-framework}/context/annotation/Configuration.html[`@Configuration`] Javadoc. 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. +`static` nested configuration class if desired. In the following example, the `OrderServiceTest` class +declares a `static` nested configuration class named `Config` that is automatically +used to load the `ApplicationContext` for the test class: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @RunWith(SpringRunner.class) // ApplicationContext will be loaded from the // static nested Config class - **@ContextConfiguration** + @ContextConfiguration <1> public class OrderServiceTest { @Configuration @@ -1900,195 +2230,225 @@ configuration class is arbitrary. In addition, a test class can contain more tha } ---- +<1> Loading configuration information from the nested class. +==== + + [[testcontext-ctx-management-mixed-config]] -===== Mixing XML, Groovy scripts, and annotated classes +===== 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 +annotated classes (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 +Furthermore, some third-party frameworks (such as 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, +(for example, 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 +the `spring-test` module support only one resource type for each 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 +frameworks may choose to support the declaration of both `locations` and `classes` through +`@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 +If you want to use resource locations (for example, XML or Groovy) and `@Configuration` +classes to configure your tests, you must pick one as the entry point, and +that one must include or import the other. For example, in XML or Groovy scripts, +you can include `@Configuration` classes by using component scanning or define them as normal +Spring beans, whereas, in a `@Configuration` class, you can use `@ImportResource` to import XML configuration files or Groovy scripts. 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. +equivalent to how you configure your application in production: In production +configuration, you define either a set of XML or Groovy resource locations or a set +of `@Configuration` classes from which your production `ApplicationContext` is loaded, +but you still have the freedom to include or import the other type of configuration. [[testcontext-ctx-management-initializers]] -===== Context configuration with context initializers +===== Context Configuration with Context Initializers -To configure an `ApplicationContext` for your tests using context initializers, annotate +To configure an `ApplicationContext` for your tests by 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 +`ApplicationContextInitializer`. The declared context initializers are then 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`). +`SmartContextLoader` in use (typically a `GenericApplicationContext`). Furthermore, the order in which the initializers are invoked depends on whether they implement Spring's `Ordered` interface or are annotated with Spring's `@Order` annotation -or the standard `@Priority` annotation. +or the standard `@Priority` annotation. The following example shows how to use initializers: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @RunWith(SpringRunner.class) // ApplicationContext will be loaded from TestConfig // and initialized by TestAppCtxInitializer - **@ContextConfiguration( + @ContextConfiguration( classes = TestConfig.class, - initializers = TestAppCtxInitializer.class)** + initializers = TestAppCtxInitializer.class) <1> public class MyTest { // class body... } ---- +<1> Loading configuration with an initializer. +==== -It is also possible to omit the declaration of XML configuration files, Groovy scripts, +You can also omit the declaration of XML configuration files, Groovy scripts, or annotated classes in `@ContextConfiguration` entirely and instead declare only -`ApplicationContextInitializer` classes which are then responsible for registering beans +`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. +files or configuration classes. The following example shows how to do so: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @RunWith(SpringRunner.class) // ApplicationContext will be initialized by EntireAppInitializer // which presumably registers beans in the context - **@ContextConfiguration(initializers = EntireAppInitializer.class)** + @ContextConfiguration(initializers = EntireAppInitializer.class) <1> public class MyTest { // class body... } ---- +<1> Specifying configuration by using only an initializer class. +==== + + [[testcontext-ctx-management-inheritance]] -===== Context configuration 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 +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 +Similarly, the initializers for a given test class are 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. +of extending the resource locations, annotated classes, or context initializers. If the `inheritLocations` or `inheritInitializers` attribute in `@ContextConfiguration` is set to `false`, the resource locations or annotated classes and the context -initializers, respectively, for the test class __shadow__ and effectively replace the +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"__. +In the next example, which uses XML resource locations, the `ApplicationContext` for +`ExtendedTest` is loaded from `base-config.xml` and +`extended-config.xml`, in that order. Beans defined in `extended-config.xml` can, +therefore, override (that is, replace) those defined in `base-config.xml`. +The following example shows how one class can extend another and use both its own +configuration file and the superclass's configuration file: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @RunWith(SpringRunner.class) // ApplicationContext will be loaded from "/base-config.xml" // in the root of the classpath - **@ContextConfiguration("/base-config.xml")** + @ContextConfiguration("/base-config.xml") <1> 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")** + @ContextConfiguration("/extended-config.xml") <2> public class ExtendedTest extends BaseTest { // class body... } ---- +<1> Configuration file defined in the superclass. +<2> Configuration file defined in the subclass. +==== -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`. +Similarly, in the next example, which uses annotated classes, the +`ApplicationContext` for `ExtendedTest` are loaded from the `BaseConfig` and +`ExtendedConfig` classes, in that order. Beans defined in `ExtendedConfig` can, therefore, +override (that is, replace) those defined in `BaseConfig`. +The following example shows how one class can extend another and use both its own +configuration class and the superclass's configuration class: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @RunWith(SpringRunner.class) // ApplicationContext will be loaded from BaseConfig - **@ContextConfiguration(classes = BaseConfig.class)** + @ContextConfiguration(classes = BaseConfig.class) <1> public class BaseTest { // class body... } // ApplicationContext will be loaded from BaseConfig and ExtendedConfig - **@ContextConfiguration(classes = ExtendedConfig.class)** + @ContextConfiguration(classes = ExtendedConfig.class) <2> public class ExtendedTest extends BaseTest { // class body... } ---- +<1> Configuration class defined in the superclass. +<2> Configuration class defined in the subclass. +==== -In the following example that uses context initializers, the `ApplicationContext` for -`ExtendedTest` will be initialized using `BaseInitializer` __and__ +In the next example, which uses context initializers, the `ApplicationContext` for +`ExtendedTest` are initialized by using `BaseInitializer` and `ExtendedInitializer`. Note, however, that the order in which the initializers are invoked depends on whether they implement Spring's `Ordered` interface or are annotated with Spring's `@Order` annotation or the standard `@Priority` annotation. +The following example shows how one class can extend another and use both its own +initializer and the superclass's initializer: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @RunWith(SpringRunner.class) // ApplicationContext will be initialized by BaseInitializer - **@ContextConfiguration(initializers = BaseInitializer.class)** + @ContextConfiguration(initializers = BaseInitializer.class) <1> public class BaseTest { // class body... } // ApplicationContext will be initialized by BaseInitializer // and ExtendedInitializer - **@ContextConfiguration(initializers = ExtendedInitializer.class)** + @ContextConfiguration(initializers = ExtendedInitializer.class) <2> public class ExtendedTest extends BaseTest { // class body... } ---- +<1> Initializer defined in the superclass. +<2> Initializer defined in the subclass. +==== + + [[testcontext-ctx-management-env-profiles]] -===== Context configuration with environment 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 +environments and profiles (AKA "`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] -==== -`@ActiveProfiles` may be used with any implementation of the new `SmartContextLoader` +NOTE: You can use `@ActiveProfiles` with any implementation of the new `SmartContextLoader` SPI, but `@ActiveProfiles` is not supported with implementations of the older `ContextLoader` SPI. + +Consider two examples with XML configuration and `@Configuration` classes: + ==== - -Let's take a look at some examples with XML configuration and `@Configuration` classes. - [source,xml,indent=0] [subs="verbatim,quotes"] ---- @@ -2156,29 +2516,31 @@ Let's take a look at some examples with XML configuration and `@Configuration` c } } ---- +==== -When `TransferServiceTest` is run, its `ApplicationContext` will be loaded from the +When `TransferServiceTest` is run, its `ApplicationContext` is 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. +`app-config.xml`, you can see 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, in the +`dev` profile, and in the `default` profile. -By annotating `TransferServiceTest` with `@ActiveProfiles("dev")` we instruct the Spring +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. +`{"dev"}`. As a result, an embedded database is created and populated with test data, +and the `accountRepository` bean is wired with a reference to the development +`DataSource`. That is 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 +are included only when no other profile is specifically activated. You can use this 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. +integration test with `@Configuration` classes instead of XML: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2278,31 +2640,33 @@ integration test but using `@Configuration` classes instead of XML. } } ---- +==== 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 +* `TransferServiceConfig`: Acquires a `dataSource` through dependency injection by 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 +by using 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 +annotation, you can declare `@ActiveProfiles` once on a base class, and +subclasses 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`. +annotations) has been moved to an abstract superclass, `AbstractIntegrationTest`: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2336,10 +2700,12 @@ annotations) has been moved to an abstract superclass, `AbstractIntegrationTest` } } ---- +==== `@ActiveProfiles` also supports an `inheritProfiles` attribute that can be used to -disable the inheritance of active profiles. +disable the inheritance of active profiles, as the following example shows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2351,23 +2717,25 @@ disable the inheritance of active profiles. // 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: +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. +* 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. +* Other concerns. -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. +To resolve active bean definition profiles programmatically, you can implement a custom +`ActiveProfilesResolver` and register it by using the `resolver` attribute of +`@ActiveProfiles`. For further information, see the +corresponding {api-spring-framework}/test/context/ActiveProfilesResolver.html[Javadoc]. The following example demonstrates how to implement and register a +custom `OperatingSystemActiveProfilesResolver`: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2397,103 +2765,120 @@ corresponding javadocs. } } ---- +==== + + [[testcontext-ctx-management-property-sources]] -===== Context configuration with test 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 +environment with a hierarchy of property sources. Since Spring 4.1, you can configure integration +tests with test-specific property sources. In contrast to the +`@PropertySource` annotation used on `@Configuration` classes, you can declare the `@TestPropertySource` +annotation on a test class to declare resource locations for test +properties files or inlined properties. These test property sources are added to the set of `PropertySources` in the `Environment` for the `ApplicationContext` loaded for the annotated integration test. [NOTE] ==== -`@TestPropertySource` may be used with any implementation of the `SmartContextLoader` +You can use `@TestPropertySource` 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 +through the `getPropertySourceLocations()` and `getPropertySourceProperties()` methods in `MergedContextConfiguration`. ==== -*Declaring test property sources* +====== Declaring Test Property Sources -Test properties files can be configured via the `locations` or `value` attribute of -`@TestPropertySource` as shown in the following example. +You can configure test properties files by using the `locations` or `value` attribute of +`@TestPropertySource`. 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 +Each path is interpreted as a Spring `Resource`. A plain path (for example, +`"test.properties"`) is 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 resource (for example: `"/org/example/test.xml"`). A path that +references a URL (for example, a path prefixed with `classpath:`, `file:`, `http:`, and others) +is loaded by using the specified resource protocol. Resource location wildcards (such as +`**/*.properties`) are not permitted: Each location must evaluate to exactly one `.properties` or `.xml` resource. +The folowing example uses a test properties file: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @ContextConfiguration - @TestPropertySource("/test.properties") + @TestPropertySource("/test.properties") <1> public class MyIntegrationTests { // class body... } ---- +<1> Specifying a properties file with an absolute path. +==== -_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 +You can configure inlined properties in the form of key-value pairs by using the +`properties` attribute of `@TestPropertySource`, as shown in the next example. All +key-value pairs are 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"` +* `key=value` +* `key:value` +* `key value` +The following example sets two inlined properties: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @ContextConfiguration - @TestPropertySource(properties = {"timezone = GMT", "port: 4242"}) + @TestPropertySource(properties = {"timezone = GMT", "port: 4242"}) <1> public class MyIntegrationTests { // class body... } ---- +<1> Setting two properties by using two variations of the key-value syntax. +==== -*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 + +====== Default Properties File Detection + +If `@TestPropertySource` is declared as an empty annotation (that is, without explicit +values for the `locations` or `properties` attributes), an attempt is 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. +properties file is `classpath:com/example/MyTest.properties`. If the default cannot be +detected, an `IllegalStateException` is thrown. -*Precedence* +====== 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 +system's environment, Java system properties, or property sources added by the +application declaratively by using `@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 +In the next example, the `timezone` and `port` properties and any properties +defined in `"/test.properties"` 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. +are overridden by the inlined properties declared by using the `properties` attribute. +The following example shows how to specify properties both in a file and inline: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2506,29 +2891,33 @@ will be overridden by the _inlined_ properties declared via the `properties` att // class body... } ---- +==== -*Inheriting and overriding test property sources* +====== 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 +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.., +by superclasses. Thus, subclasses have the option of extending the locations and +inlined properties. Note that properties that appear later shadow (that is, override) properties of the same name that appear earlier. In addition, the aforementioned precedence rules apply for inherited test property sources as well. If the `inheritLocations` or `inheritProperties` attribute in `@TestPropertySource` is set -to `false`, the locations or inlined properties, respectively, for the test class __shadow__ +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. +In the next example, the `ApplicationContext` for `BaseTest` is loaded by using +only the `base.properties` file as a test property source. In contrast, the +`ApplicationContext` for `ExtendedTest` is loaded by using the `base.properties` +and `extended.properties` files as test property source locations. +The following example shows how to define properties in both a subclass and its superclass +by using `properties` files: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2544,11 +2933,14 @@ only the `"base.properties"` file as a test property source. In contrast, the // ... } ---- +==== -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. +In the next example, the `ApplicationContext` for `BaseTest` is loaded by using only +the inlined `key1` property. In contrast, the `ApplicationContext` for `ExtendedTest` is +loaded by using the inlined_`key1` and `key2` properties. The following example shows how +to define properties in both a subclass and its superclass by using inline properties: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2564,39 +2956,44 @@ loaded using the _inlined_ `key1` and `key2` properties. // ... } ---- +==== + + [[testcontext-ctx-management-web]] -===== Loading a WebApplicationContext +===== 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 +of a standard `ApplicationContext`, you can 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 +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` is set to `src/main/webapp`. This is interpreted as a path +relative to the root of your JVM (normally the path to your project). If you are +familiar with the directory structure of a web application in a Maven project, you +know that `src/main/webapp` is the default location for the root of your WAR. If you +need to override this default, you can provide an alternate path to the +`@WebAppConfiguration` annotation (for example, `@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. +system, you can 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` +Note that Spring's testing support for `WebApplicationContext` implementations is on par with its +support for standard `ApplicationContext` implementations. When testing with a `WebApplicationContext`, you are free to declare XML configuration files, Groovy scripts, or `@Configuration` -classes via `@ContextConfiguration`. You are of course also free to use any other test -annotations such as `@ActiveProfiles`, `@TestExecutionListeners`, `@Sql`, `@Rollback`, -etc. +classes by using `@ContextConfiguration`. You are also free to use any other test +annotations, such as `@ActiveProfiles`, `@TestExecutionListeners`, `@Sql`, `@Rollback`, +and others. -The following examples demonstrate some of the various configuration options for loading -a `WebApplicationContext`. +The remaining examples in this section show some of the various configuration options for loading +a `WebApplicationContext`. The following example shows the TestContext framework's support +for convention over configuration: .Conventions +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2605,25 +3002,30 @@ a `WebApplicationContext`. // defaults to "file:src/main/webapp" @WebAppConfiguration - // detects "WacTests-context.xml" in same package - // or static nested @Configuration class + // detects "WacTests-context.xml" in the same package + // or static nested @Configuration classes @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 +If you annotate a test class with `@WebAppConfiguration` without +specifying a resource base path, the resource path effectively defaults +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 +tries to detect the presence of your configuration by using conventions +(that is, `WacTests-context.xml` in the same package as the `WacTests` class or static nested `@Configuration` classes). + +The following example shows how to explicitly declare a resource base path with +`@WebAppConfiguration` and an XML resource location with `@ContextConfiguration`: + .Default resource semantics +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2639,14 +3041,17 @@ nested `@Configuration` classes). //... } ---- +==== -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. +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. + +The following example shows that we can override the default resource semantics for both +annotations by specifying a Spring resource prefix: .Explicit resource semantics +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2662,32 +3067,33 @@ whereas, `@ContextConfiguration` resource locations are classpath based. //... } ---- +==== -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 +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 <> 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 +`WebApplicationContext`, this <> sets +up default thread-local state by using Spring Web's `RequestContextHolder` before each test +method and creates a `MockHttpServletRequest`, a `MockHttpServletResponse`, and a +`ServletWebRequest` based on the base resource path configured with `@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. +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 +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 +perform assertions after invoking your web component. The following example shows 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 +`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"] ---- @@ -2716,126 +3122,130 @@ whereas, the other mocks are managed per test method by the //... } ---- +==== -- + + [[testcontext-ctx-management-caching]] -===== Context 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 +for a test, that context is 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__. +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 +An `ApplicationContext` can be uniquely identified by the combination of configuration parameters that is used to load it. Consequently, the unique combination -of configuration parameters is used to generate a __key__ under which the context is +of configuration parameters is 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)__ -* `contextCustomizers` __(from ContextCustomizerFactory)__ -* `contextLoader` __(from @ContextConfiguration)__ -* `parent` __(from @ContextHierarchy)__ -* `activeProfiles` __(from @ActiveProfiles)__ -* `propertySourceLocations` __(from @TestPropertySource)__ -* `propertySourceProperties` __(from @TestPropertySource)__ -* `resourceBasePath` __(from @WebAppConfiguration)__ +* `locations` (from `@ContextConfiguration`) +* `classes` (from `@ContextConfiguration`) +* `contextInitializerClasses` (from `@ContextConfiguration`) +* `contextCustomizers` (from `ContextCustomizerFactory`) +* `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 +loads the corresponding `ApplicationContext` and stores 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 +is 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] ==== -The Spring TestContext framework stores application contexts in a __static__ cache. This +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. +tests execute in separate processes, the static cache is cleared between each test +execution, which effectively disables 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 +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] +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. +framework cannot cache application contexts between test classes, and the +build process runs significantly more slowly as a result. ==== Since Spring Framework 4.3, the size of the context cache is bounded with a default -maximum size of 32. Whenever the maximum size is reached, a _least recently used_ (LRU) -eviction policy is used to evict and close stale contexts. The maximum size can be -configured from the command line or a build script by setting a JVM system property named -`spring.test.context.cache.maxSize`. As an alternative, the same property can be set -programmatically via the `SpringProperties` API. +maximum size of 32. Whenever the maximum size is reached, a least recently used (LRU) +eviction policy is used to evict and close stale contexts. You can configure the maximum size +from the command line or a build script by setting a JVM system property named +`spring.test.context.cache.maxSize`. As an alternative, you can set the same property +programmatically by using the `SpringProperties` API. 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 +the underlying context cache, you can 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 -- +(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 <>). 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` +context before running the next test. Note that support for the `@DirtiesContext` annotation is provided by the `DirtiesContextBeforeModesTestExecutionListener` and the -`DirtiesContextTestExecutionListener` which are enabled by default. +`DirtiesContextTestExecutionListener`, which are enabled by default. [[testcontext-ctx-management-ctx-hierarchies]] -===== Context 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 +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` instances. For +example, if you are developing a Spring MVC web application, you typically have a +root `WebApplicationContext` loaded by Spring's `ContextLoaderListener` and a child +`WebApplicationContext` loaded by 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 +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. -Since Spring Framework 3.2.2, it is possible to write integration tests that use context -hierarchies by declaring context configuration via the `@ContextHierarchy` annotation, +Since Spring Framework 3.2.2, you can write integration tests that use context +hierarchies by declaring context configuration with 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 is declared on multiple classes within a test class hierarchy, you can also +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 (that is, 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 4 based examples demonstrate common configuration scenarios for +The remaining JUnit 4-based examples in this section show 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). +Spring MVC web application by declaring a context hierarchy that consists of two levels, +one for the root `WebApplicationContext` (loaded by using the `TestAppConfig` +`@Configuration` class) and one for the dispatcher servlet `WebApplicationContext` +(loaded by using the `WebConfig` `@Configuration` class). The `WebApplicationContext` that +is autowired into the test instance is the one for the child context (that is, the +lowest context in the hierarchy). The following listing shows this configuration scenario: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2853,24 +3263,25 @@ lowest context in the hierarchy). // ... } ---- - +==== -- .Class hierarchy with implicit parent context -- -The following test classes define a context hierarchy within a test class hierarchy. +The test classes in this example 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 +`@ContextHierarchy`. Consequently, subclasses of `AbstractWebTests` can optionally +participate in a context hierarchy or 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 +`AbstractWebTests` and define a context hierarchy by using `@ContextHierarchy`. The result is +that three application contexts are 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. +in `AbstractWebTests` is set as the parent context for each of the contexts loaded +for the concrete subclasses. The following listing shows this configuration scenario: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2885,23 +3296,26 @@ for the concrete subclasses. @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` +The classes in this exxample show 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 the `name` attribute in `@ContextConfiguration` 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"}`. +configuration for the `child` hierarchy level, by ensuring that the names +declared in the `name` attribute in `@ContextConfiguration` are both `child`. The +result is that three application contexts are 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` +is set as the parent context for the contexts loaded from `/user-config.xml` +and `{"/user-config.xml", "/order-config.xml"}`. The following listing shows this +configuration scenario: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2917,17 +3331,19 @@ and `{"/user-config.xml", "/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 +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 the `inheritLocations` flag in `@ContextConfiguration` 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"`. +application context for `ExtendedTests` is loaded only from +`/test-user-config.xml` and has its parent set to the context loaded from +`/app-config.xml`. The following listing shows this configuration scenario: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -2946,47 +3362,42 @@ application context for `ExtendedTests` will be loaded only from )) public class ExtendedTests extends BaseTests {} ---- +==== .Dirtying a context within a context hierarchy -[NOTE] -==== -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 +NOTE: If you use `@DirtiesContext` in a test whose context is configured as part of a context +hierarchy, you can use the `hierarchyMode` flag to control how the context cache is +cleared. For further details, see the discussion of `@DirtiesContext` in <> and the -`@DirtiesContext` javadocs. -==== +{api-spring-framework}/test/annotation/DirtiesContext.html[`@DirtiesContext` Javadoc]. -- -[[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 +[[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 330. -[TIP] -==== - -The TestContext framework does not instrument the manner in which a test instance is -instantiated. Thus the use of `@Autowired` or `@Inject` for constructors has no effect +TIP: The TestContext framework does not instrument the manner in which a test instance is +instantiated. Thus, the use of `@Autowired` or `@Inject` for constructors has no effect for test classes. -==== -Because `@Autowired` is used to perform <>, if you have multiple bean definitions of the same type, you cannot rely on this +Because `@Autowired` is used to perform <>, 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 `@Qualifier`. As of Spring 3.0, you can 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 +If you do not want dependency injection applied to your test instances, 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` @@ -3002,15 +3413,16 @@ is presented after all sample code listings. The dependency injection behavior in the following code listings is not specific to JUnit 4. 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()` +The following examples make calls to static assertion methods, such as `assertNotNull()`, but without prepending the call with `Assert`. In such cases, assume that the method was properly imported through an `import static` declaration that is not shown in the example. ==== The first code listing shows a JUnit 4 based implementation of the test class that uses -`@Autowired` for field injection. +`@Autowired` for field injection: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3030,10 +3442,12 @@ The first code listing shows a JUnit 4 based implementation of the test class th } } ---- +==== -Alternatively, you can configure the class to use `@Autowired` for setter injection as -seen below. +Alternatively, you can configure the class to use `@Autowired` for setter injection, as +follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3057,11 +3471,13 @@ seen below. } } ---- +==== The preceding code listings use the same XML context file referenced by the -`@ContextConfiguration` annotation (that is, `repository-config.xml`), which looks like -this: +`@ContextConfiguration` annotation (that is, `repository-config.xml`). The following +shows this configuration: +==== [source,xml,indent=0] [subs="verbatim,quotes"] ---- @@ -3082,16 +3498,18 @@ this: ---- +==== [NOTE] -==== +===== If you are extending from a Spring-provided test base class that happens to use `@Autowired` on one of its setter methods, you might have multiple beans of the affected -type defined in your application context: for example, multiple `DataSource` beans. In +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. +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"] ---- @@ -3105,38 +3523,41 @@ method in the superclass as well. // ... ---- +==== 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 `` declarations within the corresponding `` 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). -==== +is used as a fallback qualifier value, so you can effectively also point to a specific +bean by name there (as shown earler, assuming that `myDataSource` is the bean `id`). +===== + [[testcontext-web-scoped-beans]] -==== Testing request and session scoped beans +==== Testing Request- and Session-scoped Beans -<> have been supported by -Spring since the early years, and since Spring 3.2 it's a breeze to test your -request-scoped and session-scoped beans by following these steps. +Spring has supported <> +since the early years. Since Spring 3.2, you can 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 +. 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 +. 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. +. Invoke your web component that you retrieved from the configured + `WebApplicationContext` (with dependency injection). +. Perform assertions against the mocks. -The following code snippet displays the XML configuration for a login use case. Note +The nexxt code snippet shows 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 <> 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. +Also, the `LoginAction` is instantiated by using <> that +retrieve the username and password from the current HTTP request. In our test, we +want to configure these request parameters through the mock managed by the TestContext +framework. The following listing shows the configuration for this use case: .Request-scoped bean configuration +==== [source,xml,indent=0] ---- @@ -3153,17 +3574,19 @@ framework. ---- +==== -In `RequestScopedBeanTests` we inject both the `UserService` (i.e., the subject under +In `RequestScopedBeanTests`, we inject both the `UserService` (that is, 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 +`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. +`userService`, we are assured that the user service has access to the request-scoped +`loginAction` for the current `MockHttpServletRequest` (that is, the one in which we just set +parameters). We can then perform assertions against the results based on the known +inputs for the username and password. The following listing shows how to do so: .Request-scoped bean test +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3185,15 +3608,17 @@ inputs for the username and password. } } ---- +==== -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. +The following code snippet is similar to the one we saw earlier 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 by using a +SpEL expression that retrieves the theme from the current HTTP session. In our test, +we need to configure a theme in the mock session managed by the TestContext +framework. The following example shows how to do so: .Session-scoped bean configuration +==== [source,xml,indent=0] [subs="verbatim,quotes"] ---- @@ -3210,16 +3635,18 @@ framework. ---- +==== -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 +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. +configured theme. The following example shows how to do so: .Session-scoped bean test +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3240,56 +3667,57 @@ configured theme. } } ---- +==== + [[testcontext-tx]] -==== Transaction management +==== Transaction Management In the TestContext framework, transactions are managed by the -`TransactionalTestExecutionListener` which is configured by default, even if you do not +`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. +`ApplicationContext` that is loaded with `@ContextConfiguration` semantics (further +details are provided later). In addition, you must declare Spring's `@Transactional` +annotation either at the class or the method level for your tests. [[testcontext-tx-test-managed-transactions]] -===== 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 +Test-managed transactions are transactions that are managed declaratively by using the +`TransactionalTestExecutionListener` or programmatically by using `TestTransaction` (described +later). You should not confuse such transactions with Spring-managed transactions +(those managed directly by Spring within the `ApplicationContext` loaded for tests) +or application-managed transactions (those managed programmatically within +application code that is invoked by tests). Spring-managed and application-managed +transactions typically participate in test-managed transactions. However, you should use caution +if Spring-managed or application-managed transactions are configured with +any propagation type other than `REQUIRED` or `SUPPORTS` (see the discussion on <> for details). + + [[testcontext-tx-enabling-transactions]] -===== Enabling and disabling 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 +transaction that is, by default, 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 +class hierarchy runs within a transaction. Test methods that are not annotated +with `@Transactional` (at the class or method level) are not 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. +`propagation` type set to `NOT_SUPPORTED` are not run within a transaction. -__Note that <> and <> -are preconfigured for transactional support at the class level.__ +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 -<>, 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 <> for an additional example. +a Hibernate-based `UserRepository`: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3333,6 +3761,15 @@ See <> for an additional example. } } ---- +==== + +As explained in +<>, there is no need to clean up the +database after the `createUser()` method runs, since any changes made to the +database are automatically rolled back by the `TransactionalTestExecutionListener`. +See <> for an additional example. + + [[testcontext-tx-rollback-and-commit-behavior]] ===== Transaction rollback and commit behavior @@ -3343,18 +3780,19 @@ via the `@Commit` and `@Rollback` annotations. See the corresponding entries in <> section for further details. [[testcontext-tx-programmatic-tx-mgt]] -===== Programmatic transaction management +===== Programmatic Transaction Management -Since 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_ +Since Spring Framework 4.1, you can interact with test-managed transactions +programmatically by using the static methods in `TestTransaction`. For example, you can use +`TestTransaction` 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. +The following example demonstrates some of the features of `TestTransaction` (see the +{api-spring-framework}/test/context/transaction/TestTransaction.html[Javadoc for `TestTransaction`] for further details): +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3385,52 +3823,58 @@ javadocs for `TestTransaction` for further details. } } ---- +==== + + [[testcontext-tx-before-and-after-tx]] -===== Executing code outside of a transaction +===== Running Code Outside of a Transaction -Occasionally you need to execute certain code before or after a transactional test method +Occasionally, you may 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 to commit the transaction). +prior to running your test or to verify expected transactional commit behavior after your +test runs (if the test was configured to commit the transaction). `TransactionalTestExecutionListener` supports the `@BeforeTransaction` and -`@AfterTransaction` annotations exactly for such scenarios. Simply annotate any `void` +`@AfterTransaction` annotations for exactly such scenarios. You can annotate any `void` method in a test class or any `void` default method in a test interface with one of these -annotations, and the `TransactionalTestExecutionListener` ensures that your __before -transaction method__ or __after transaction method__ is executed at the appropriate time. +annotations, and the `TransactionalTestExecutionListener` ensures that your before +transaction method or after transaction method runs at the appropriate time. -[TIP] -==== -Any __before methods__ (such as methods annotated with JUnit Jupiter's `@BeforeEach`) and -any __after methods__ (such as methods annotated with JUnit Jupiter's `@AfterEach`) are -executed __within__ a transaction. In addition, methods annotated with -`@BeforeTransaction` or `@AfterTransaction` are naturally not executed for test methods +TIP: Any before methods (such as methods annotated with JUnit Jupiter's `@BeforeEach`) and +any after methods (such as methods annotated with JUnit Jupiter's `@AfterEach`) are +run within a transaction. In addition, methods annotated with +`@BeforeTransaction` or `@AfterTransaction` are not run for test methods that are not configured to run within a transaction. -==== + + [[testcontext-tx-mgr-config]] -===== Configuring a transaction manager +===== 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`, a -_qualifier_ may be declared via `@Transactional("myTxMgr")` or +defined in the Spring `ApplicationContext` for the test. If there are multiple +instances of `PlatformTransactionManager` within the test's `ApplicationContext`, you can declare +a qualifier by using `@Transactional("myTxMgr")` or `@Transactional(transactionManager = "myTxMgr")`, or `TransactionManagementConfigurer` -can be implemented by an `@Configuration` class. Consult the javadocs for -`TestContextTransactionUtils.retrieveTransactionManager()` for details on the algorithm +can be implemented by an `@Configuration` class. Consult the {api-spring-framework}/test/context/transaction/TestContextTransactionUtils.html#retrieveTransactionManager[Javadoc 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 +===== Demonstration of All Transaction-related Annotations -The following JUnit 4 based example displays a _fictitious_ integration testing scenario -highlighting all transaction-related annotations. The example is **not** intended to +The following JUnit 4 based example displays a fictitious integration testing scenario +that highlights 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 <> section for further +See the <> section for further information and configuration examples. <> contains an additional example using `@Sql` for -declarative SQL script execution with default transaction rollback semantics. +Transaction management for `@Sql`>> contains an additional example that uses `@Sql` for +declarative SQL script execution with default transaction rollback semantics. The +following example shows the relevant annotations in bold: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3469,20 +3913,22 @@ declarative SQL script execution with default transaction rollback semantics. } ---- +==== [[testcontext-tx-false-positives]] .Avoid false positives when testing ORM code [NOTE] -==== +===== When you test application code that manipulates the state of a Hibernate session or JPA -persistence context, make sure to __flush__ the underlying unit of work within test -methods that execute that code. Failing to flush the underlying unit of work 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 +persistence context, make sure to flush the underlying unit of work within test +methods that run that code. Failing to flush the underlying unit of work can produce +false positives: Your test passes, but the same code throws an exception in a live, +production environment. Note that this applies to any ORM framework that maintains an +in-memory unit of work. 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 any ORM frameworks that maintain an -in-memory __unit of work__. +flushing the session: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3509,9 +3955,11 @@ in-memory __unit of work__. // ... ---- +==== -Or for JPA: +The following example shows matching methods for JPA: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3539,10 +3987,12 @@ Or for JPA: // ... ---- ==== +===== + [[testcontext-executing-sql]] -==== Executing SQL scripts +==== 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. @@ -3571,22 +4021,23 @@ integration test methods. `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 +needs better than some of the other alternatives described later. See the {api-spring-framework}/jdbc/datasource/init/ScriptUtils.html[Javadoc] 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 +`ResourceDatabasePopulator` provides an object-based API for programmatically +populating, initializing, or cleaning up a database by 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 +used when parsing and running the scripts. Each of the configuration options has +a reasonable default value. See the {api-spring-framework}/jdbc/datasource/init/ResourceDatabasePopulator.html[Javadoc] for details on default values. To +run 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`. +schema and test data, sets the statement separator to `@@`, and executes the +scripts against a `DataSource`: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3601,37 +4052,43 @@ scripts against a `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 +and running SQL scripts. Similarly, the `executeSqlScript(..)` methods in <> and <> -internally use a `ResourceDatabasePopulator` for executing SQL scripts. Consult the javadocs +internally use a `ResourceDatabasePopulator` to run SQL scripts. See the Javadoc 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 +In addition to the aforementioned mechanisms for running SQL scripts +programmatically, you can declaratively configure SQL scripts in the Spring +TestContext Framework. Specifically, you can declare the `@Sql` annotation 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 +run against a given database 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. +`@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 Jupiter based integration test class. +====== Path Resource Semantics +Each path is interpreted as a Spring `Resource`. A plain path (for example, +`"schema.sql"`) is 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 resource (for example, `"/org/example/schema.sql"`). A path +that references a URL (for example, a path prefixed with `classpath:`, `file:`, `http:`, and others) +is loaded by using the specified resource protocol. + +The following example shows how to use `@Sql` at the class level and at the method +level within a JUnit Jupiter based integration test class: + +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3651,32 +4108,37 @@ level within a JUnit Jupiter based integration test class. } } ---- +==== -*Default script detection* -If no SQL scripts are specified, an attempt will be made to detect a `default` script + +====== Default Script Detection + +If no SQL scripts are specified, an attempt is made to detect a `default` script, depending on where `@Sql` is declared. If a default cannot be detected, an -`IllegalStateException` will be thrown. +`IllegalStateException` is 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 +* 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"`. + `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 + +====== Declaring Multiple `@Sql` Sets + +If you need to configure multiple sets of SQL scripts 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 +different execution phases per set, you can declare multiple instances of +`@Sql`. With Java 8, you can use `@Sql` as a repeatable annotation. Otherwise, you can use the +`@SqlGroup` annotation 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. +The following example shows how to use `@Sql` as a repeatable annotation with +Java 8: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3687,10 +4149,15 @@ single-line comments. // 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. +In the scenario presented in the preceding example, the `test-schema.sql` script uses a different syntax for +single-line comments. +The following example is identical to the preceding example, 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"] ---- @@ -3703,15 +4170,16 @@ grouped together within `@SqlGroup` for compatibility with Java 6 and Java 7. // execute code that uses the test schema and test data } ---- +==== -*Script execution phases* +====== 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. +By default, SQL scripts are executed before the corresponding test method. However, +if you need to run a particular set of scripts after the test method (for +example, to clean up database state), you can use the `executionPhase` attribute in `@Sql`, +as the following example shows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3730,58 +4198,61 @@ statically imported from `Sql.TransactionMode` and `Sql.ExecutionPhase` respecti // to the database outside of the test's transaction } ---- +==== -*Script configuration with `@SqlConfig`* +Note that `ISOLATED` and `AFTER_TEST_METHOD` are +statically imported from `Sql.TransactionMode` and `Sql.ExecutionPhase`, respectively. -Configuration for script parsing and error handling can be configured via the +====== Script Configuration with `@SqlConfig` + +You can configure script parsing and error handling by using 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 +class, `@SqlConfig` serves as global configuration for all SQL scripts within the test +class hierarchy. When declared directly by using 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, +default value, which is documented in the Javadoc 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 +have an explicit default value of either `""` (for Strings) or `DEFAULT` (for enumerations). This +approach lets local declarations of `@SqlConfig` 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. +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 `` XML namespace element. Consult the javadocs -of individual attributes in `@Sql` and `@SqlConfig` for details. +provided by the `` XML namespace element. See the Javadoc +of individual attributes in {api-spring-framework}/test/context/jdbc/Sql.html[`@Sql`] and {api-spring-framework}/test/context/jdbc/SqlConfig.html[`@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 +By default, the `SqlScriptsTestExecutionListener` infer the desired transaction +semantics for scripts configured by using `@Sql`. Specifically, SQL scripts are run +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 +`@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 +`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 +you can specify explicit names by setting the `dataSource` and `transactionManager` attributes +of `@SqlConfig`. Furthermore, you can control the transaction propagation behavior by setting +the `transactionMode` attribute of `@SqlConfig` (for example, whether scripts should be +run 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 Jupiter 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 test method or within the `/test-data.sql` script) -will be automatically rolled back by the `TransactionalTestExecutionListener` (see -<> for details). +manual, the Javadoc for {api-spring-framework}/test/context/jdbc/SqlConfig.html[`@SqlConfig`] and {api-spring-framework}/test/context/jdbc/SqlScriptsTestExecutionListener.html[`SqlScriptsTestExecutionListener`] provide +detailed information, and the following example shows a typical testing scenario +that uses JUnit Jupiter and transactional tests with `@Sql`: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3814,35 +4285,40 @@ will be automatically rolled back by the `TransactionalTestExecutionListener` (s } } ---- +==== + +Note that there is no need to +clean up the database after the `usersTest()` method is run, since any changes made +to the database (either within the test method or within the `/test-data.sql` script) +are automatically rolled back by the `TransactionalTestExecutionListener` (see +<> for details). + [[testcontext-parallel-test-execution]] -==== Parallel test execution +==== Parallel Test Execution Spring Framework 5.0 introduces basic support for executing tests in parallel within a -single JVM when using the _Spring TestContext Framework_. In general this means that most +single JVM when using the Spring TestContext Framework. In general, this means that most test classes or test methods can be executed in parallel without any changes to test code or configuration. -[TIP] -==== -For details on how to set up parallel test execution, consult the documentation for your +TIP: For details on how to set up parallel test execution, see the documentation for your testing framework, build tool, or IDE. -==== Keep in mind that the introduction of concurrency into your test suite can result in -unexpected side effects, strange runtime behavior, and tests that only fail intermittently +unexpected side effects, strange runtime behavior, and tests that fail intermittently or seemingly randomly. The Spring Team therefore provides the following general guidelines -for when __not__ to execute tests in parallel. +for when not to execute tests in parallel. -__Do not execute tests in parallel if:__ +Do not execute tests in parallel if the tests: -* Tests make use of Spring's `@DirtiesContext` support. -* Tests make use of JUnit 4's `@FixMethodOrder` support or any testing framework feature - that is designed to ensure that test methods execute in a particular order. Note, +* Use Spring's `@DirtiesContext` support. +* Use JUnit 4's `@FixMethodOrder` support or any testing framework feature + that is designed to ensure that test methods run in a particular order. Note, however, that this does not apply if entire test classes are executed in parallel. -* Tests change the state of shared services or systems such as a database, message broker, - filesystem, etc. This applies to both in-memory and external systems. +* Change the state of shared services or systems such as a database, message broker, + filesystem, and others. This applies to both in-memory and external systems. [TIP] ==== @@ -3851,46 +4327,47 @@ for the current test is no longer active, this typically means that the `ApplicationContext` was removed from the `ContextCache` in a different thread. This may be due to the use of `@DirtiesContext` or due to automatic eviction from the -`ContextCache`. If `@DirtiesContext` is the culprit, you will either need to find a way +`ContextCache`. If `@DirtiesContext` is the culprit, you either need to find a way to avoid using `@DirtiesContext` or exclude such tests from parallel execution. If the maximum size of the `ContextCache` has been exceeded, you can increase the maximum size of the cache. See the discussion on <> for details. ==== -[WARNING] -==== -Parallel test execution in the Spring TestContext Framework is only possible if the -underlying `TestContext` implementation provides a _copy constructor_ as explained in the -javadocs for `TestContext`. The `DefaultTestContext` used in Spring provides such a -constructor; however, if you use a third-party library that provides a custom -`TestContext` implementation, you will need to verify if it is suitable for parallel test +WARNING: Parallel test execution in the Spring TestContext Framework is only possible if the +underlying `TestContext` implementation provides a copy constructor, as explained in the +{api-spring-framework}/test/context/TestContext.html[Javadoc for `TestContext`]. The `DefaultTestContext` used in Spring provides such a +constructor. However, if you use a third-party library that provides a custom +`TestContext` implementation, you need to verify that it is suitable for parallel test execution. -==== + [[testcontext-support-classes]] -==== TestContext Framework support classes +==== TestContext Framework Support Classes + +This section describes the various classes that support the Spring TestContext Framework. + + [[testcontext-junit4-runner]] ===== Spring JUnit 4 Runner -The __Spring TestContext Framework__ offers full integration with JUnit 4 through a +The Spring TestContext Framework offers full integration with JUnit 4 through a custom runner (supported on JUnit 4.12 or higher). By annotating test classes with `@RunWith(SpringJUnit4ClassRunner.class)` or the shorter `@RunWith(SpringRunner.class)` -variant, developers can implement standard JUnit 4 based unit and integration tests and -simultaneously reap the benefits of the TestContext framework such as support for loading +variant, developers can implement standard JUnit 4-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. If you would like to use the Spring TestContext Framework with an -alternative runner such as JUnit 4's `Parameterized` or third-party runners such as the -`MockitoJUnitRunner`, you may optionally use <> instead. -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`. +The following code listing shows the minimal requirements for configuring a test class +to run with the custom Spring `Runner`: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3904,30 +4381,37 @@ empty list in order to disable the default listeners, which otherwise would requ } } ---- +==== + +In the preceding example, `@TestExecutionListeners` is configured with an +empty list, to disable the default listeners, which otherwise would require an +`ApplicationContext` to be configured through `@ContextConfiguration`. + + [[testcontext-junit4-rules]] ===== Spring JUnit 4 Rules The `org.springframework.test.context.junit4.rules` package provides the following JUnit -4 rules (supported on JUnit 4.12 or higher). +4 rules (supported on JUnit 4.12 or higher): * `SpringClassRule` * `SpringMethodRule` -`SpringClassRule` is a JUnit `TestRule` that supports _class-level_ features of the -_Spring TestContext Framework_; whereas, `SpringMethodRule` is a JUnit `MethodRule` that -supports instance-level and method-level features of the _Spring TestContext Framework_. +`SpringClassRule` is a JUnit `TestRule` that supports class-level features of the +Spring TestContext Framework, whereas `SpringMethodRule` is a JUnit `MethodRule` that +supports instance-level and method-level features of the Spring TestContext Framework. In contrast to the `SpringRunner`, Spring's rule-based JUnit support has the advantage -that it is independent of any `org.junit.runner.Runner` implementation and can therefore -be combined with existing alternative runners like JUnit 4's `Parameterized` or third-party -runners such as the `MockitoJUnitRunner`. - -In order to support the full functionality of the TestContext framework, a -`SpringClassRule` must be combined with a `SpringMethodRule`. The following example -demonstrates the proper way to declare these rules in an integration test. +of being independent of any `org.junit.runner.Runner` implementation and can, therefore, +be combined with existing alternative runners (such as JUnit 4's `Parameterized`) or third-party +runners (such as the `MockitoJUnitRunner`). +To support the full functionality of the TestContext framework, you must combine a +`SpringClassRule` with a `SpringMethodRule`. The following example +shows the proper way to declare these rules in an integration test: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -3947,75 +4431,76 @@ demonstrates the proper way to declare these rules in an integration test. } } ---- +==== [[testcontext-support-classes-junit4]] -===== JUnit 4 support classes +===== JUnit 4 Support Classes The `org.springframework.test.context.junit4` package provides the following support -classes for JUnit 4 based test cases (supported on JUnit 4.12 or higher). +classes for JUnit 4-based test cases (supported on JUnit 4.12 or higher): * `AbstractJUnit4SpringContextTests` * `AbstractTransactionalJUnit4SpringContextTests` `AbstractJUnit4SpringContextTests` is an abstract base test class that integrates the -__Spring TestContext Framework__ with explicit `ApplicationContext` testing support in +Spring TestContext Framework with explicit `ApplicationContext` testing support in a JUnit 4 environment. When you extend `AbstractJUnit4SpringContextTests`, you can -access a `protected` `applicationContext` instance variable that can be used to perform +access a `protected` `applicationContext` instance variable that you can use to perform explicit bean lookups or to test the state of the context as a whole. -`AbstractTransactionalJUnit4SpringContextTests` is an abstract __transactional__ extension +`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 +`AbstractTransactionalJUnit4SpringContextTests`, you can access a `protected` `jdbcTemplate` +instance variable that you can used to run SQL statements to query the database. You can use such +queries to confirm database state both before and after running 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 <>. As mentioned in <>, `AbstractTransactionalJUnit4SpringContextTests` -also provides convenience methods which delegate to methods in `JdbcTestUtils` using the +also provides convenience methods that delegate to methods in `JdbcTestUtils` by using the aforementioned `jdbcTemplate`. Furthermore, `AbstractTransactionalJUnit4SpringContextTests` -provides an `executeSqlScript(..)` method for executing SQL scripts against the configured +provides an `executeSqlScript(..)` method for running SQL scripts against the configured `DataSource`. -[TIP] -==== -These classes are a convenience for extension. If you do not want your test classes to be +TIP: These classes are a convenience for extension. If you do not want your test classes to be tied to a Spring-specific class hierarchy, you can configure your own custom test classes by using `@RunWith(SpringRunner.class)` or <>. -==== + + [[testcontext-junit-jupiter-extension]] ===== SpringExtension for JUnit Jupiter -The __Spring TestContext Framework__ offers full integration with the _JUnit Jupiter_ -testing framework introduced in JUnit 5. By annotating test classes with -`@ExtendWith(SpringExtension.class)`, developers can implement standard JUnit Jupiter -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 +The Spring TestContext Framework offers full integration with the JUnit Jupiter +testing framework, introduced in JUnit 5. By annotating test classes with +`@ExtendWith(SpringExtension.class)`, you can implement standard JUnit Jupiter-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. -Furthermore, thanks to the rich extension API in JUnit Jupiter, Spring is able to provide +Furthermore, thanks to the rich extension API in JUnit Jupiter, Spring can provide the following features above and beyond the feature set that Spring supports for JUnit 4 -and TestNG. +and TestNG: * Dependency injection for test constructors, test methods, and test lifecycle callback - methods - - See <> for further details. -* Powerful support for link:http://junit.org/junit5/docs/current/user-guide/#extensions-conditions[_conditional test execution_] - based on SpEL expressions, environment variables, system properties, etc. - - See the documentation for `@EnabledIf` and `@DisabledIf` in + methods. + See <> for further details. +* Powerful support for link:http://junit.org/junit5/docs/current/user-guide/#extensions-conditions[conditional test execution] + based on SpEL expressions, environment variables, system properties, and so on. + See the documentation for `@EnabledIf` and `@DisabledIf` in <> for further details and examples. -* Custom _composed annotations_ that combine annotations from Spring **and** JUnit +* Custom composed annotations that combine annotations from Spring and JUnit Jupiter. - - See the `@TransactionalDevTestConfig` and `@TransactionalIntegrationTest` examples in + See the `@TransactionalDevTestConfig` and `@TransactionalIntegrationTest` examples in <> for further details. -The following code listing demonstrates how to configure a test class to use the -`SpringExtension` in conjunction with `@ContextConfiguration`. +The following code listing shows how to configure a test class to use the +`SpringExtension` in conjunction with `@ContextConfiguration`: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4031,14 +4516,16 @@ The following code listing demonstrates how to configure a test class to use the } } ---- +==== -Since annotations in JUnit 5 can also be used as meta-annotations, Spring is able to -provide `@SpringJUnitConfig` and `@SpringJUnitWebConfig` __composed annotations__ to +Since you can also use annotations in JUnit 5 as meta-annotations, Spring can +provide the `@SpringJUnitConfig` and `@SpringJUnitWebConfig` composed annotations to simplify the configuration of the test `ApplicationContext` and JUnit Jupiter. -For example, the following example uses `@SpringJUnitConfig` to reduce the amount of -configuration used in the previous example. +The following example uses `@SpringJUnitConfig` to reduce the amount of +configuration used in the previous example: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4053,10 +4540,12 @@ configuration used in the previous example. } } ---- +==== Similarly, the following example uses `@SpringJUnitWebConfig` to create a -`WebApplicationContext` for use with JUnit Jupiter. +`WebApplicationContext` for use with JUnit Jupiter: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4071,46 +4560,48 @@ Similarly, the following example uses `@SpringJUnitWebConfig` to create a } } ---- +==== See the documentation for `@SpringJUnitConfig` and `@SpringJUnitWebConfig` in <> for further details. -[[testcontext-junit-jupiter-di]] -===== Dependency Injection with the SpringExtension -The `SpringExtension` implements the + +[[testcontext-junit-jupiter-di]] +===== Dependency Injection with `SpringExtension` + +`SpringExtension` implements the link:http://junit.org/junit5/docs/current/user-guide/#extensions-parameter-resolution[`ParameterResolver`] -extension API from JUnit Jupiter which allows Spring to provide dependency injection for +extension API from JUnit Jupiter, which lets Spring provide dependency injection for test constructors, test methods, and test lifecycle callback methods. -Specifically, the `SpringExtension` is able to inject dependencies from the test's -`ApplicationContext` into test constructors and methods annotated with `@BeforeAll`, +Specifically, `SpringExtension` can inject dependencies from the test's +`ApplicationContext` into test constructors and methods that are annotated with `@BeforeAll`, `@AfterAll`, `@BeforeEach`, `@AfterEach`, `@Test`, `@RepeatedTest`, `@ParameterizedTest`, -etc. +and others. + + [[testcontext-junit-jupiter-di-constructor]] ====== Constructor Injection If a parameter in a constructor for a JUnit Jupiter test class is of type `ApplicationContext` (or a sub-type thereof) or is annotated or meta-annotated with -`@Autowired`, `@Qualifier`, or `@Value`, Spring will inject the value for that specific -parameter with the corresponding bean from the test's `ApplicationContext`. A test -constructor can also be directly annotated with `@Autowired` if all of the parameters +`@Autowired`, `@Qualifier`, or `@Value`, Spring injects the value for that specific +parameter with the corresponding bean from the test's `ApplicationContext`. You can also directly annotate a test +constructor with `@Autowired` if all of the parameters should be supplied by Spring. -[WARNING] -==== -If the constructor for a test class is itself annotated with `@Autowired`, Spring will -assume the responsibility for resolving **all** parameters in the constructor. -Consequently, no other `ParameterResolver` registered with JUnit Jupiter will be able to +WARNING: If the constructor for a test class is itself annotated with `@Autowired`, Spring +assumes the responsibility for resolving _all_ parameters in the constructor. +Consequently, no other `ParameterResolver` registered with JUnit Jupiter can resolve parameters for such a constructor. -==== -In the following example, Spring will inject the `OrderService` bean from the +In the following example, Spring injects the `OrderService` bean from the `ApplicationContext` loaded from `TestConfig.class` into the -`OrderServiceIntegrationTests` constructor. Note as well that this feature allows test -dependencies to be `final` and therefore _immutable_. +`OrderServiceIntegrationTests` constructor. +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4127,18 +4618,25 @@ dependencies to be `final` and therefore _immutable_. // tests that use the injected OrderService } ---- +==== + +Note that this feature lets test +dependencies be `final` and therefore immutable. + + [[testcontext-junit-jupiter-di-method]] ====== Method Injection If a parameter in a JUnit Jupiter test method or test lifecycle callback method is of type `ApplicationContext` (or a sub-type thereof) or is annotated or meta-annotated with -`@Autowired`, `@Qualifier`, or `@Value`, Spring will inject the value for that specific +`@Autowired`, `@Qualifier`, or `@Value`, Spring injects the value for that specific parameter with the corresponding bean from the test's `ApplicationContext`. -In the following example, Spring will inject the `OrderService` from the -`ApplicationContext` loaded from `TestConfig.class` into the `deleteOrder()` test method. +In the following example, Spring injects the `OrderService` from the +`ApplicationContext` loaded from `TestConfig.class` into the `deleteOrder()` test method: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4151,16 +4649,16 @@ In the following example, Spring will inject the `OrderService` from the } } ---- +==== -Due to the robustness of the `ParameterResolver` support in JUnit Jupiter, it is also -possible to have multiple dependencies injected into a single method not only from Spring +Due to the robustness of the `ParameterResolver` support in JUnit Jupiter, you can also +have multiple dependencies injected into a single method, not only from Spring but also from JUnit Jupiter itself or other third-party extensions. -The following example demonstrates how to have both Spring and JUnit Jupiter inject -dependencies into the `placeOrderRepeatedly()` test method simultaneously. Note that the -use of `@RepeatedTest` from JUnit Jupiter allows the test method to gain access to the -`RepetitionInfo`. +The following example shows how to have both Spring and JUnit Jupiter inject +dependencies into the `placeOrderRepeatedly()` test method simultaneously. +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4176,97 +4674,100 @@ use of `@RepeatedTest` from JUnit Jupiter allows the test method to gain access } } ---- +==== + +Note that the +use of `@RepeatedTest` from JUnit Jupiter lets the test method gain access to the +`RepetitionInfo`. + + [[testcontext-support-classes-testng]] -===== TestNG support classes +===== TestNG Support Classes The `org.springframework.test.context.testng` package provides the following support -classes for TestNG based test cases. +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 +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 +access a `protected` `applicationContext` instance variable that you can use to perform explicit bean lookups or to test the state of the context as a whole. -`AbstractTransactionalTestNGSpringContextTests` is an abstract __transactional__ extension +`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 +`AbstractTransactionalTestNGSpringContextTests`, you can access a `protected` `jdbcTemplate` +instance variable that you can used to execute SQL statements to query the database. You can use such +queries to confirm database state both before and after running 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 <>. As mentioned in <>, `AbstractTransactionalTestNGSpringContextTests` -also provides convenience methods which delegate to methods in `JdbcTestUtils` using the +also provides convenience methods that delegate to methods in `JdbcTestUtils` by using the aforementioned `jdbcTemplate`. Furthermore, `AbstractTransactionalTestNGSpringContextTests` -provides an `executeSqlScript(..)` method for executing SQL scripts against the configured +provides an `executeSqlScript(..)` method for running SQL scripts against the configured `DataSource`. -[TIP] -==== -These classes are a convenience for extension. If you do not want your test classes to be +TIP: These classes are a convenience for extension. If you do not want your test classes to be tied to a Spring-specific class hierarchy, you can configure your own custom test classes -by using `@ContextConfiguration`, `@TestExecutionListeners`, and so on, and by manually +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. -==== [[spring-mvc-test-framework]] === Spring MVC Test Framework -The __Spring MVC Test framework__ provides first class support for testing Spring MVC -code using a fluent API that can be used with JUnit, TestNG, or any other testing -framework. It's built on the +The Spring MVC Test framework provides first class support for testing Spring MVC +code with a fluent API that you can use with JUnit, TestNG, or any other testing +framework. It is built on the {api-spring-framework}/mock/web/package-summary.html[Servlet API mock objects] -from the `spring-test` module and hence does _not_ use a running Servlet container. It +from the `spring-test` module and, hence, does not use a running Servlet container. It uses the `DispatcherServlet` to provide full Spring MVC runtime behavior and provides support -for loading actual Spring configuration with the __TestContext framework__ in addition to a -standalone mode in which controllers may be instantiated manually and tested one at a time. +for loading actual Spring configuration with the TestContext framework in addition to a +standalone mode, in which you can manually instantiate controllers and test them one at a time. -__Spring MVC Test__ also provides client-side support for testing code that uses -the `RestTemplate`. Client-side tests mock the server responses and also do _not_ +Spring MVC Test also provides client-side support for testing code that uses +the `RestTemplate`. Client-side tests mock the server responses and also do not use a running server. -[TIP] -==== -Spring Boot provides an option to write full, end-to-end integration tests that include -a running server. If this is your goal please have a look at the +TIP: Spring Boot provides an option to write full, end-to-end integration tests that include +a running server. If this is your goal, see the {doc-spring-boot}/html/boot-features-testing.html#boot-features-testing-spring-boot-applications[Spring Boot reference page]. For more information on the differences between out-of-container and end-to-end integration tests, see <>. -==== + [[spring-mvc-test-server]] ==== Server-Side Tests -It's easy to write a plain unit test for a Spring MVC controller using JUnit or TestNG: -simply instantiate the controller, inject it with mocked or stubbed dependencies, and call -its methods passing `MockHttpServletRequest`, `MockHttpServletResponse`, etc., as necessary. +You can write a plain unit test for a Spring MVC controller bt using JUnit or TestNG. +To do so, instantiate the controller, inject it with mocked or stubbed dependencies, and call +its methods (passing `MockHttpServletRequest`, `MockHttpServletResponse`, and others, as necessary). However, when writing such a unit test, much remains untested: for example, request mappings, data binding, type conversion, validation, and much more. Furthermore, other controller methods such as `@InitBinder`, `@ModelAttribute`, and `@ExceptionHandler` may also be invoked as part of the request processing lifecycle. -The goal of __Spring MVC Test__ is to provide an effective way for testing controllers +The goal of Spring MVC Test is to provide an effective way to test controllers by performing requests and generating responses through the actual `DispatcherServlet`. -__Spring MVC Test__ builds on the familiar <> 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 a few notable -exceptions as explained in <>. Here is a -JUnit Jupiter based example of using Spring MVC Test: +For the most part, everything should work as it does at runtime with a few notable +exceptions, as explained in <>. The following +JUnit Jupiter-based example uses Spring MVC Test: +==== [source,java,indent=0] ---- import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; @@ -4292,40 +4793,46 @@ JUnit Jupiter based example of using Spring MVC Test: } } ---- +==== -The above test relies on the `WebApplicationContext` support of the __TestContext framework__ -for loading Spring configuration from an XML configuration file located in the same package +The preceding test relies on the `WebApplicationContext` support of the TestContext framework +to load Spring configuration from an XML configuration file located in the same package as the test class, but Java-based and Groovy-based configuration are also supported. See these https://github.com/spring-projects/spring-framework/tree/master/spring-test/src/test/java/org/springframework/test/web/servlet/samples/context[sample tests]. -The `MockMvc` instance is used to perform a `GET` request to `"/accounts/1"` and verify -that the resulting response has status 200, the content type is `"application/json"`, and the -response body has a JSON property called "name" with the value "Lee". The `jsonPath` +The MockMvc instance is used to perform a `GET` request to `/accounts/1` and verify +that the resulting response has status 200, the content type is `application/json`, and the +response body has a JSON property called `name` with the value `Lee`. The `jsonPath` syntax is supported through the Jayway https://github.com/jayway/JsonPath[JsonPath -project]. There are lots of other options for verifying the result of the performed -request that will be discussed below. +project]. Many other options for verifying the result of the performed +request are discussed later in this document. + + [[spring-mvc-test-server-static-imports]] ===== Static Imports -The fluent API in the example above requires a few static imports such as +The fluent API in the example from the <> 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 +types that match `MockMvc*`. If you use Eclipse or the Eclipse-based Spring Tool Suite, be sure to add them as +"`favorite static members`" in the Eclipse preferences under +Java -> Editor -> Content Assist -> Favorites. Doing so lets you use content +assist after typing the first character of the static method name. Other IDEs (such as +IntelliJ) may not require any additional configuration. Check the support for code completion on static members. + + [[spring-mvc-test-server-setup-options]] ===== Setup Choices -There are two main options for creating an instance of `MockMvc`. -The first is to load Spring MVC configuration through the __TestContext -framework__, which loads the Spring configuration and injects a `WebApplicationContext` -into the test to use to build a `MockMvc` instance: +You have two main options for creating an instance of MockMvc. +The first is to load Spring MVC configuration through the TestContext +framework, which loads the Spring configuration and injects a `WebApplicationContext` +into the test to use to build a MockMvc instance. The following example shows how to do so: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4348,12 +4855,14 @@ into the test to use to build a `MockMvc` instance: } ---- +==== -The second is to simply create a controller instance manually without loading Spring -configuration. Instead basic default configuration, roughly comparable to that of -the MVC JavaConfig or the MVC namespace, is automatically created and can be customized -to a degree: +Your second option is to manually create a controller instance without loading Spring +configuration. Instead, basic default configuration, roughly comparable to that of +the MVC JavaConfig or the MVC namespace, is automatically created. You can customize it +to a degree. The following example shows how to do so: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4370,16 +4879,18 @@ to a degree: } ---- +==== Which setup option should you use? -The __"webAppContextSetup"__ loads your actual Spring MVC configuration resulting in a -more complete integration test. Since the __TestContext framework__ caches the loaded +The `webAppContextSetup` loads your actual Spring MVC configuration, resulting in a +more complete integration test. Since the TestContext framework caches the loaded Spring configuration, it helps keep tests running fast, even as you introduce more tests in your test suite. 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: +Spring configuration to remain focused on testing the web layer. The following +example declares a mock service with Mockito: +==== [source,xml,indent=0] [subs="verbatim,quotes"] ---- @@ -4387,10 +4898,12 @@ example of declaring a mock service with Mockito: ---- +==== -You can then inject the mock service into the test in order set up and verify -expectations: +You can then inject the mock service into the test to set up and verify your +expectations, as the following example shows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4411,28 +4924,32 @@ expectations: } ---- +==== -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 on style +The `standaloneSetup`, on the other hand, is a little closer to a unit test. It tests +one controller at a time. You can manually inject the controller with mock dependencies, +and it does not involve loading Spring configuration. Such tests are more focused on 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 +MVC configuration is required to work, and so on. The `standaloneSetup` is also a very convenient way to write ad-hoc tests to verify specific behavior or to debug an issue. -Just like with any "integration vs. unit testing" debate, there is no right or wrong -answer. However, using the "standaloneSetup" does imply the need for additional -"webAppContextSetup" tests in order to verify your Spring MVC configuration. -Alternatively, you may choose to write all tests with "webAppContextSetup" in order to +As with most "`integration versus unit testing`" debates, there is no right or wrong +answer. However, using the `standaloneSetup` does imply the need for additional +`webAppContextSetup` tests in order to verify your Spring MVC configuration. +Alternatively, you can write all your tests with `webAppContextSetup`, in order to always test against your actual Spring MVC configuration. + + [[spring-mvc-test-server-setup-steps]] ===== Setup Features -No matter which MockMvc builder you use all `MockMvcBuilder` implementations provide -some common and very useful features. For example you can declare an `Accept` header +No matter which MockMvc builder you use, all `MockMvcBuilder` implementations provide +some common and very useful features. For example, you can declare an `Accept` header for all requests and expect a status of 200 as well as a `Content-Type` header -in all responses as follows: +in all responses, as follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4444,12 +4961,14 @@ MockMvc mockMvc = standaloneSetup(new MusicController()) .alwaysExpect(content().contentType("application/json;charset=UTF-8")) .build(); ---- +==== -In addition 3rd party frameworks (and applications) may pre-package setup -instructions like the ones through a `MockMvcConfigurer`. The Spring Framework +In addition, third-party frameworks (and applications) can pre-package setup +instructions, such as those in a `MockMvcConfigurer`. The Spring Framework has one such built-in implementation that helps to save and re-use the HTTP -session across requests. It can be used as follows: +session across requests. You can use it as follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4461,66 +4980,81 @@ session across requests. It can be used as follows: // Use mockMvc to perform requests... ---- +==== -See `ConfigurableMockMvcBuilder` for a list of all MockMvc builder features +See the {api-spring-framework}/test/web/servlet/setup/ConfigurableMockMvcBuilder.html[Javadoc for `ConfigurableMockMvcBuilder`] for a list of all MockMvc builder features or use the IDE to explore the available options. + + [[spring-mvc-test-server-performing-requests]] ===== Performing Requests -It's easy to perform requests using any HTTP method: +You can perform requests that use any HTTP method, as the following example shows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- mockMvc.perform(post("/hotels/{id}", 42).accept(MediaType.APPLICATION_JSON)); ---- +==== You can also perform file upload requests that internally use `MockMultipartHttpServletRequest` so that there is no actual parsing of a multipart -request but rather you have to set it up: +request. Rather, you have to set it up to be similar to the following example: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- mockMvc.perform(multipart("/doc").file("a1", "ABC".getBytes("UTF-8"))); ---- +==== -You can specify query parameters in URI template style: +You can specify query parameters in URI template style, as the following example shows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - mockMvc.perform(get("/hotels?foo={foo}", "bar")); + mockMvc.perform(get("/hotels?thing={thing}", "somewhere")); ---- +==== -Or you can add Servlet request parameters representing either query of form parameters: +You can also add Servlet request parameters that represent either query of form parameters, +as the following example shows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - mockMvc.perform(get("/hotels").param("foo", "bar")); + mockMvc.perform(get("/hotels").param("thing", "somewhere")); ---- +==== -If application code relies on Servlet request parameters and doesn't check the query -string explicitly (as is most often the case) then it doesn't matter which option you use. -Keep in mind however that query params provided with the URI template will be decoded while +If application code relies on Servlet request parameters and does not check the query +string explicitly (as is most often the case), it does not matter which option you use. +Keep in mind, however, that query paramaters provided with the URI template are decoded while request parameters provided through the `param(...)` method are expected to already be decoded. -In most cases it's preferable to leave out the context path and the Servlet path from +In most cases, it is preferable to leave the context path and the Servlet path out of 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: +`contextPath` and `servletPath` accordingly so that request mappings work, as the following example shows: +==== [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. Instead you can set up default request -properties: +In the preceding example, it would be cumbersome to set the `contextPath` and +`servletPath` with every performed request. Instead, you can set up default request +properties, as the following example shows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4536,39 +5070,45 @@ properties: .accept(MediaType.APPLICATION_JSON)).build(); } ---- +==== -The above properties will affect every request performed through the `MockMvc` instance. +The preceding properties affect every request performed through the MockMvc instance. If the same property is also specified on a given request, it overrides the default value. -That is why the HTTP method and URI in the default request don't matter since they must be +That is why the HTTP method and URI in the default request do not matter, 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(..)` calls after -performing a request: +You can define expectations by appending one or more `.andExpect(..)` calls after +performing a request, as the following example shows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- mockMvc.perform(get("/accounts/1")).andExpect(status().isOk()); ---- +==== `MockMvcResultMatchers.*` provides a number of expectations, some of which are further nested with more detailed expectations. Expectations fall in two general categories. The first category of assertions verifies -properties of the response: for example, the response status, headers, and content. These +properties of the response (for example, the response status, headers, and content). These are the most important results to assert. -The second category of assertions goes beyond the response. These assertions allow -one to inspect Spring MVC specific aspects such as which controller method processed +The second category of assertions goes beyond the response. These assertions let +you inspect Spring MVC specific aspects, 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. They also allow -one to inspect Servlet specific aspects such as request and session attributes. +is, what view was selected, what flash attributes were added, and so on. They also let +you inspect Servlet specific aspects, such as request and session attributes. The following test asserts that binding or validation failed: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4576,11 +5116,13 @@ The following test asserts that binding or validation failed: .andExpect(status().isOk()) .andExpect(model().attributeHasErrors("person")); ---- +==== -Many times when writing tests, it's useful to _dump_ the results of the performed request. -This can be done as follows, where `print()` is a static import from +Many times, when writing tests, it is useful to dump the results of the performed request. +You can do so as follows, where `print()` is a static import from `MockMvcResultHandlers`: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4589,31 +5131,35 @@ This can be done as follows, where `print()` is a static import from .andExpect(status().isOk()) .andExpect(model().attributeHasErrors("person")); ---- +==== As long as request processing does not cause an unhandled exception, the `print()` method -will print all the available result data to `System.out`. Spring Framework 4.2 introduced +prints all the available result data to `System.out`. Spring Framework 4.2 introduced a `log()` method and two additional variants of the `print()` method, one that accepts an `OutputStream` and one that accepts a `Writer`. For example, invoking -`print(System.err)` will print the result data to `System.err`; while invoking -`print(myWriter)` will print the result data to a custom writer. If you would like to -have the result data _logged_ instead of printed, simply invoke the `log()` method which -will log the result data as a single `DEBUG` message under the +`print(System.err)` prints the result data to `System.err`, while invoking +`print(myWriter)` prints the result data to a custom writer. If you want to +have the result data logged instead of printed, you can invoke the `log()` method, which +logs the result data as a single `DEBUG` message under the `org.springframework.test.web.servlet.result` logging category. In some cases, you may want to get direct access to the result and verify something that cannot be verified otherwise. This can be achieved by appending `.andReturn()` after all -other expectations: +other expectations, as the following example shows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- MvcResult mvcResult = mockMvc.perform(post("/persons")).andExpect(status().isOk()).andReturn(); // ... ---- +==== -If all tests repeat the same expectations you can set up common expectations once -when building the `MockMvc` instance: +If all tests repeat the same expectations, you can set up common expectations once +when building the MockMvc instance, as the following example shows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4622,25 +5168,29 @@ when building the `MockMvc` instance: .alwaysExpect(content().contentType("application/json;charset=UTF-8")) .build() ---- +==== -Note that common expectations are __always__ applied and cannot be overridden without -creating a separate `MockMvc` instance. +Note that common expectations are 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 using JsonPath expressions: +When a JSON response content contains hypermedia links created with +https://github.com/spring-projects/spring-hateoas[Spring HATEOAS], you can verify the resulting links +by using JsonPath expressions, as the following example shows: +==== [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 using XPath expressions: +https://github.com/spring-projects/spring-hateoas[Spring HATEOAS], you can verify the resulting links +by using XPath expressions: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -4648,76 +5198,86 @@ be verified using XPath expressions: 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` instance, you can register one or more Servlet `Filter` instances: +When setting up a MockMvc instance, you can register one or more Servlet `Filter` instances, +as the following example shows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- mockMvc = standaloneSetup(new PersonController()).addFilters(new CharacterEncodingFilter()).build(); ---- +==== + +Registered filters are invoked through the `MockFilterChain` from `spring-test`, and the +last filter delegates to the `DispatcherServlet`. + -Registered filters will be invoked through via the `MockFilterChain` from `spring-test`, and the -last filter will delegate to the `DispatcherServlet`. [[spring-mvc-test-vs-end-to-end-integration-tests]] -===== Differences between Out-of-Container and End-to-End Integration Tests +===== Differences Between Out-of-Container and End-to-End Integration Tests -As mentioned earlier __Spring MVC Test__ is built on the Servlet API mock objects from -the `spring-test` module and does not use a running Servlet container. Therefore +As mentioned earlier Spring MVC Test is built on the Servlet API mock objects from +the `spring-test` module and does not use a running Servlet container. Therefore, there are some important differences compared to full end-to-end integration tests with an actual client and server running. -The easiest way to think about this is starting with a blank `MockHttpServletRequest`. -Whatever you add to it is what the request will be. Things that may catch you by surprise -are that there is no context path by default, no `jsessionid` cookie, no forwarding, error, -or async dispatches, and therefore no actual JSP rendering. Instead, "forwarded" and -"redirected" URLs are saved in the `MockHttpServletResponse` and can be asserted with +The easiest way to think about this is by starting with a blank `MockHttpServletRequest`. +Whatever you add to it is what the request becomes. Things that may catch you by surprise +are that there is no context path by default; no `jsessionid` cookie; no forwarding, error, +or async dispatches; andm, therefore, no actual JSP rendering. Instead, "`forwarded`" and +"`redirected`" URLs are saved in the `MockHttpServletResponse` and can be asserted with expectations. -This means if you are using JSPs you can verify the JSP page to which the request was -forwarded, but there won't be any HTML rendered. In other words, the JSP will not be -_invoked_. Note however that all other rendering technologies which don't rely on -forwarding such as Thymeleaf and Freemarker will render HTML to the response body as -expected. The same is true for rendering JSON, XML, and other formats via `@ResponseBody` +This means that, if you use JSPs, you can verify the JSP page to which the request was +forwarded, but no HTML is rendered. In other words, the JSP is not +invoked. Note, however, that all other rendering technologies that do not rely on +forwarding, such as Thymeleaf and Freemarker, render HTML to the response body as +expected. The same is true for rendering JSON, XML, and other formats through `@ResponseBody` methods. -Alternatively you may consider the full end-to-end integration testing support from -Spring Boot via `@WebIntegrationTest`. See the -{doc-spring-boot}/html/boot-features-testing.html#boot-features-testing-spring-boot-applications[Spring Boot reference]. +Alternatively, you may consider the full end-to-end integration testing support from +Spring Boot with `@WebIntegrationTest`. See the +{doc-spring-boot}/html/boot-features-testing.html#boot-features-testing-spring-boot-applications[Spring Boot Reference Guide]. -There are pros and cons for each approach. The options provided in __Spring MVC Test__ +There are pros and cons for each approach. The options provided in Spring MVC Test are different stops on the scale from classic unit testing to full integration testing. To be certain, none of the options in Spring MVC Test fall under the category of classic -unit testing, but they _are_ a little closer to it. For example, you can isolate the web -layer by injecting mocked services into controllers, in which case you're testing the web -layer only through the `DispatcherServlet` but with actual Spring configuration, just -like you might test the data access layer in isolation from the layers above. Or you -can use the standalone setup focusing on one controller at a time and manually providing +unit testing, but they are a little closer to it. For example, you can isolate the web +layer by injecting mocked services into controllers, in which case you are testing the web +layer only through the `DispatcherServlet` but with actual Spring configuration, as +you might test the data access layer in isolation from the layers above it. Also, you +can use the stand-alone setup, focusing on one controller at a time and manually providing the configuration required to make it work. -Another important distinction when using __Spring MVC Test__ is that conceptually such -tests are on the _inside_ of the server-side so you can check what handler was used, +Another important distinction when using Spring MVC Test is that, conceptually, such +tests are the server-side, so you can check what handler was used, if an exception was handled with a HandlerExceptionResolver, what the content of the -model is, what binding errors there were, etc. That means it's easier to write -expectations since the server is not a black box as it is when testing it through -an actual HTTP client. This is generally an advantage of classic unit testing, that it's +model is, what binding errors there were, and other details. That means that it is easier to write +expectations, since the server is not a black box, as it is when testing it through +an actual HTTP client. This is generally an advantage of classic unit testing: It is easier to write, reason about, and debug but does not replace the need for full -integration tests. At the same time it's important not to lose sight of the fact that +integration tests. At the same time, it is important not to lose sight of the fact that the response is the most important thing to check. In short, there is room here for multiple styles and strategies of testing even within the same project. + + [[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 +sample tests] intended to show how to use Spring MVC Test. You can browse these examples +for further ideas. Also, the +https://github.com/spring-projects/spring-mvc-showcase[`spring-mvc-showcase`] project has full test coverage based on Spring MVC Test. @@ -4726,33 +5286,33 @@ coverage based on Spring MVC Test. Spring provides integration between <> and http://htmlunit.sourceforge.net/[HtmlUnit]. This simplifies performing end-to-end testing -when using HTML based views. This integration enables developers to: +when using HTML-based views. This integration lets you: -* Easily test HTML pages using tools such as http://htmlunit.sourceforge.net/[HtmlUnit], -http://seleniumhq.org/projects/webdriver/[WebDriver], & +* Easily test HTML pages by using tools such as http://htmlunit.sourceforge.net/[HtmlUnit], +http://seleniumhq.org/projects/webdriver/[WebDriver], and http://www.gebish.org/manual/current/testing.html#spock_junit__testng[Geb] without the -need to deploy to a Servlet container -* Test JavaScript within pages -* Optionally test using mock services to speed up testing -* Share logic between in-container end-to-end tests and out-of-container integration tests +need to deploy to a Servlet container. +* Test JavaScript within pages. +* Optionally, test using mock services to speed up testing. +* Share logic between in-container end-to-end tests and out-of-container integration tests. -[NOTE] -==== -`MockMvc` works with templating technologies that do not rely on a Servlet Container (e.g., -Thymeleaf, FreeMarker, etc.), but it does not work with JSPs since they rely on the Servlet +NOTE: MockMvc works with templating technologies that do not rely on a Servlet Container (for example, +Thymeleaf, FreeMarker, and others), but it does not work with JSPs, since they rely on the Servlet container. -==== + + [[spring-mvc-test-server-htmlunit-why]] ===== Why HtmlUnit Integration? -The most obvious question that comes to mind is, "Why do I need this?". The answer is best +The most obvious question that comes to mind is "`Why do I need this?`" The answer is best found by exploring a very basic sample application. Assume you have a Spring MVC web application that supports CRUD operations on a `Message` object. The application also supports paging through all messages. How would you go about testing it? -With Spring MVC Test, we can easily test if we are able to create a `Message`. +With Spring MVC Test, we can easily test if we are able to create a `Message`, as follows: +==== [source,java,indent=0] ---- MockHttpServletRequestBuilder createMessage = post("/messages/") @@ -4763,10 +5323,12 @@ With Spring MVC Test, we can easily test if we are able to create a `Message`. .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/messages/123")); ---- +==== -What if we want to test our form view that allows us to create the message? For example, +What if we want to test the form view that lets us create the message? For example, assume our form looks like the following snippet: +==== [source,xml,indent=0] ----
@@ -4783,21 +5345,25 @@ assume our form looks like the following snippet:
---- +==== -How do we ensure that our form will produce the correct request to create a new message? A -naive attempt would look like this: +How do we ensure that our form produce the correct request to create a new message? A +naive attempt might resemble the following: +==== [source,java,indent=0] ---- mockMvc.perform(get("/messages/form")) .andExpect(xpath("//input[@name='summary']").exists()) .andExpect(xpath("//textarea[@name='text']").exists()); ---- +==== This test has some obvious drawbacks. If we update our controller to use the parameter -`message` instead of `text`, our form test would continue to pass even though the HTML -form is out of synch with the controller. To resolve this we can combine our two tests. +`message` instead of `text`, our form test continues to pass, even though the HTML +form is out of synch with the controller. To resolve this we can combine our two tests, as follows: +==== [[spring-mvc-test-server-htmlunit-mock-mvc-test]] [source,java,indent=0] ---- @@ -4815,91 +5381,103 @@ form is out of synch with the controller. To resolve this we can combine our two .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/messages/123")); ---- +==== This would reduce the risk of our test incorrectly passing, but there are still some -problems. +problems: -* What if we have multiple forms on our page? Admittedly we could update our xpath - expressions, but they get more complicated the more factors we take into account (Are the - fields the correct type? Are the fields enabled? etc.). +* What if we have multiple forms on our page? Admittedly, we could update our XPath + expressions, but they get more complicated as we take more factors into account: Are the + fields the correct type? Are the fields enabled? And so on. * Another issue is that we are doing double the work we would expect. We must first verify the view, and then we submit the view with the same parameters we just - verified. Ideally this could be done all at once. -* Finally, there are some things that we still cannot account for. For example, what if the + verified. Ideally, this could be done all at once. +* Finally, we still cannot account for some things. For example, what if the form has JavaScript validation that we wish to test as well? The overall problem is that testing a web page does not involve a single interaction. Instead, it is a combination of how the user interacts with a web page and how that web page interacts with other resources. For example, the result of a form view is used as -the input to a user for creating a message. In addition, our form view may potentially -utilize additional resources which impact the behavior of the page, such as JavaScript +the input to a user for creating a message. In addition, our form view can potentially +use additional resources that impact the behavior of the page, such as JavaScript validation. + + [[spring-mvc-test-server-htmlunit-why-integration]] -====== Integration testing to the rescue? +====== Integration Testing to the Rescue? -To resolve the issues above we could perform end-to-end integration testing, but this has -some obvious drawbacks. Consider testing the view that allows us to page through the messages. -We might need the following tests. +To resolve the issues mentioned earler, we could perform end-to-end integration testing, but this has +some drawbacks. Consider testing the view that lets us page through the messages. +We might need the following tests: -* Does our page display a notification to the user indicating that no results are available +* Does our page display a notification to the user to indicate that no results are available when the messages are empty? * Does our page properly display a single message? * Does our page properly support paging? -To set up these tests, we would need to ensure our database contained the proper messages -in it. This leads to a number of additional challenges. +To set up these tests, we need to ensure our database contains the proper messages. +This leads to a number of additional challenges: -* Ensuring the proper messages are in the database can be tedious; consider foreign key - constraints. -* Testing can become slow since each test would need to ensure that the database is in the +* Ensuring the proper messages are in the database can be tedious. (Consider foreign key + constraints.) +* Testing can become slow, since each test would need to ensure that the database is in the correct state. * Since our database needs to be in a specific state, we cannot run tests in parallel. -* Performing assertions on things like auto-generated ids, timestamps, etc. can be difficult. +* Performing assertions on such items as auto-generated ids, timestamps, and others can be difficult. These challenges do not mean that we should abandon end-to-end integration testing altogether. Instead, we can reduce the number of end-to-end integration tests by -refactoring our detailed tests to use mock services which will execute much faster, more -reliably, and without side effects. We can then implement a small number of _true_ +refactoring our detailed tests to use mock services that run much faster, more +reliably, and without side effects. We can then implement a small number of true end-to-end integration tests that validate simple workflows to ensure that everything works together properly. + + [[spring-mvc-test-server-htmlunit-why-mockmvc]] ====== Enter HtmlUnit Integration So how can we achieve a balance between testing the interactions of our pages and still -retain good performance within our test suite? The answer is: "By integrating MockMvc -with HtmlUnit." +retain good performance within our test suite? The answer is: "`By integrating MockMvc +with HtmlUnit.`" + + [[spring-mvc-test-server-htmlunit-options]] ====== HtmlUnit Integration Options -There are a number of ways to integrate `MockMvc` with HtmlUnit. +You have a number of options when you want to integrate MockMvc with HtmlUnit: * <>: Use this option if you want to use the raw HtmlUnit libraries. * <>: Use this option to ease development and reuse code between integration and end-to-end testing. -* <>: Use this option if you would -like to use Groovy for testing, ease development, and reuse code between integration and +* <>: Use this option if you want +to use Groovy for testing, ease development, and reuse code between integration and end-to-end testing. + + [[spring-mvc-test-server-htmlunit-mah]] ===== MockMvc and HtmlUnit -This section describes how to integrate `MockMvc` and HtmlUnit. Use this option if you +This section describes how to integrate MockMvc and HtmlUnit. Use this option if you want to use the raw HtmlUnit libraries. + + [[spring-mvc-test-server-htmlunit-mah-setup]] ====== MockMvc and HtmlUnit Setup First, make sure that you have included a test dependency on `net.sourceforge.htmlunit:htmlunit`. -In order to use HtmlUnit with Apache HttpComponents 4.5+, you will need to use HtmlUnit +In order to use HtmlUnit with Apache HttpComponents 4.5+, you need to use HtmlUnit 2.18 or higher. -We can easily create an HtmlUnit `WebClient` that integrates with `MockMvc` using the -`MockMvcWebClientBuilder` as follows. +We can easily create an HtmlUnit `WebClient` that integrates with MockMvc by using the +`MockMvcWebClientBuilder`, as follows: +==== [source,java,indent=0] ---- @Autowired @@ -4914,39 +5492,39 @@ We can easily create an HtmlUnit `WebClient` that integrates with `MockMvc` usin .build(); } ---- - -[NOTE] ==== -This is a simple example of using `MockMvcWebClientBuilder`. For advanced usage see + +NOTE: This is a simple example of using `MockMvcWebClientBuilder`. For advanced usage, see <> -==== -This will ensure that any URL referencing `localhost` as the server will be directed to -our `MockMvc` instance without the need for a real HTTP connection. Any other URL will be -requested using a network connection as normal. This allows us to easily test the use of +This ensures that any URL that references `localhost` as the server is directed to +our MockMvc instance without the need for a real HTTP connection. Any other URL is +requested by using a network connection, as normal. This lets us easily test the use of CDNs. + + [[spring-mvc-test-server-htmlunit-mah-usage]] ====== MockMvc and HtmlUnit Usage -Now we can use HtmlUnit as we normally would, but without the need to deploy our +Now we can use HtmlUnit as we normally would but without the need to deploy our application to a Servlet container. For example, we can request the view to create -a message with the following. +a message with the following: +==== [source,java,indent=0] ---- HtmlPage createMsgFormPage = webClient.getPage("http://localhost/messages/form"); ---- +==== -[NOTE] -==== -The default context path is `""`. Alternatively, we can specify the context path as -illustrated in <>. -==== +NOTE: The default context path is `""`. Alternatively, we can specify the context path, as +described in <>. Once we have a reference to the `HtmlPage`, we can then fill out the form and submit -it to create a message. +it to create a message, as the following example shows: +==== [source,java,indent=0] ---- HtmlForm form = createMsgFormPage.getHtmlElementById("messageForm"); @@ -4957,10 +5535,12 @@ it to create a message. HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit"); HtmlPage newMessagePage = submit.click(); ---- +==== Finally, we can verify that a new message was created successfully. The following -assertions use the http://joel-costigliola.github.io/assertj/[AssertJ] library. +assertions use the http://joel-costigliola.github.io/assertj/[AssertJ] library: +==== [source,java,indent=0] ---- assertThat(newMessagePage.getUrl().toString()).endsWith("/messages/123"); @@ -4971,26 +5551,30 @@ assertions use the http://joel-costigliola.github.io/assertj/[AssertJ] library. String text = newMessagePage.getHtmlElementById("text").getTextContent(); assertThat(text).isEqualTo("In case you didn't know, Spring Rocks!"); ---- +==== -This improves on our <> in a -number of ways. First we no longer have to explicitly verify our form and then create a +The preceding code improves on our <> in a +number of ways. First, we no longer have to explicitly verify our form and then create a request that looks like the form. Instead, we request the form, fill it out, and submit it, thereby significantly reducing the overhead. Another important factor is that http://htmlunit.sourceforge.net/javascript.html[HtmlUnit -uses the Mozilla Rhino engine] to evaluate JavaScript. This means that we can test the -behavior of JavaScript within our pages as well! +uses the Mozilla Rhino engine] to evaluate JavaScript. This means that we can also test the +behavior of JavaScript within our pages. -Refer to the http://htmlunit.sourceforge.net/gettingStarted.html[HtmlUnit documentation] +See the http://htmlunit.sourceforge.net/gettingStarted.html[HtmlUnit documentation] for additional information about using HtmlUnit. + + [[spring-mvc-test-server-htmlunit-mah-advanced-builder]] -====== Advanced MockMvcWebClientBuilder +====== Advanced `MockMvcWebClientBuilder` In the examples so far, we have used `MockMvcWebClientBuilder` in the simplest way possible, by building a `WebClient` based on the `WebApplicationContext` loaded for us by the Spring -TestContext Framework. This approach is repeated here. +TestContext Framework. This approach is repeated in the following example: +==== [source,java,indent=0] ---- @Autowired @@ -5005,9 +5589,11 @@ TestContext Framework. This approach is repeated here. .build(); } ---- +==== -We can also specify additional configuration options. +We can also specify additional configuration options, as the following example shows: +==== [source,java,indent=0] ---- WebClient webClient; @@ -5025,10 +5611,12 @@ We can also specify additional configuration options. .build(); } ---- +==== -As an alternative, we can perform the exact same setup by configuring the `MockMvc` -instance separately and supplying it to the `MockMvcWebClientBuilder` as follows. +As an alternative, we can perform the exact same setup by configuring the MockMvc +instance separately and supplying it to the `MockMvcWebClientBuilder`, as follows: +==== [source,java,indent=0] ---- MockMvc mockMvc = MockMvcBuilders @@ -5045,57 +5633,59 @@ instance separately and supplying it to the `MockMvcWebClientBuilder` as follows .useMockMvcForHosts("example.com","example.org") .build(); ---- - -This is more verbose, but by building the `WebClient` with a `MockMvc` instance we have -the full power of `MockMvc` at our fingertips. - -[TIP] ==== -For additional information on creating a `MockMvc` instance refer to + +This is more verbose, but, by building the `WebClient` with a MockMvc instance, we have +the full power of MockMvc at our fingertips. + +TIP: For additional information on creating a MockMvc instance, see <>. -==== + + [[spring-mvc-test-server-htmlunit-webdriver]] ===== MockMvc and WebDriver -In the previous sections, we have seen how to use `MockMvc` in conjunction with the raw -HtmlUnit APIs. In this section, we will leverage additional abstractions within the Selenium +In the previous sections, we have seen how to use MockMvc in conjunction with the raw +HtmlUnit APIs. In this section, we use additional abstractions within the Selenium http://docs.seleniumhq.org/projects/webdriver/[WebDriver] to make things even easier. + + [[spring-mvc-test-server-htmlunit-webdriver-why]] ====== Why WebDriver and MockMvc? -We can already use HtmlUnit and `MockMvc`, so why would we want to use `WebDriver`? The -Selenium `WebDriver` provides a very elegant API that allows us to easily organize our code. -To better understand, let's explore an example. +We can already use HtmlUnit and MockMvc, so why would we want to use WebDriver? The +Selenium WebDriver provides a very elegant API that lets us easily organize our code. +To better show how it works, we explore an example in this section. -[NOTE] -==== -Despite being a part of http://docs.seleniumhq.org/[Selenium], WebDriver does not require +NOTE: Despite being a part of http://docs.seleniumhq.org/[Selenium], WebDriver does not require a Selenium Server to run your tests. -==== Suppose we need to ensure that a message is created properly. The tests involve finding the HTML form input elements, filling them out, and making various assertions. -This approach results in numerous, separate tests because we want to test error +This approach results in numerous separate tests because we want to test error conditions as well. For example, we want to ensure that we get an error if we fill out only part of the form. If we fill out the entire form, the newly created message should be displayed afterwards. -If one of the fields were named "summary", then we might have something like the -following repeated in multiple places within our tests. +If one of the fields were named "`summary`", we might have something that resembles the +following repeated in multiple places within our tests: +==== [source,java,indent=0] ---- HtmlTextInput summaryInput = currentPage.getHtmlElementById("summary"); summaryInput.setValueAttribute(summary); ---- +==== -So what happens if we change the `id` to "smmry"? Doing so would force us to update all -of our tests to incorporate this change! Of course, this violates the _DRY Principle_; so -we should ideally extract this code into its own method as follows. +So what happens if we change the `id` to `smmry`? Doing so would force us to update all +of our tests to incorporate this change. This violates the DRY principle, so +we should ideally extract this code into its own method, as follows: +==== [source,java,indent=0] ---- public HtmlPage createMessage(HtmlPage currentPage, String summary, String text) { @@ -5108,12 +5698,14 @@ we should ideally extract this code into its own method as follows. summaryInput.setValueAttribute(summary); } ---- +==== -This ensures that we do not have to update all of our tests if we change the UI. +Doing so ensures that we do not have to update all of our tests if we change the UI. -We might even take this a step further and place this logic within an Object that -represents the `HtmlPage` we are currently on. +We might even take this a step further and place this logic within an `Object` that +represents the `HtmlPage` we are currently on, as the following example shows: +==== [source,java,indent=0] ---- public class CreateMessagePage { @@ -5148,21 +5740,25 @@ represents the `HtmlPage` we are currently on. } } ---- +==== -Formerly, this pattern is known as the +Formerly, this pattern was known as the https://github.com/SeleniumHQ/selenium/wiki/PageObjects[Page Object Pattern]. While we can -certainly do this with HtmlUnit, WebDriver provides some tools that we will explore in the +certainly do this with HtmlUnit, WebDriver provides some tools that we explore in the following sections to make this pattern much easier to implement. + + [[spring-mvc-test-server-htmlunit-webdriver-setup]] ====== MockMvc and WebDriver Setup To use Selenium WebDriver with the Spring MVC Test framework, make sure that your project includes a test dependency on `org.seleniumhq.selenium:selenium-htmlunit-driver`. -We can easily create a Selenium `WebDriver` that integrates with `MockMvc` using the -`MockMvcHtmlUnitDriverBuilder` as follows. +We can easily create a Selenium WebDriver that integrates with MockMvc by using the +`MockMvcHtmlUnitDriverBuilder` as the following example shows: +==== [source,java,indent=0] ---- @Autowired @@ -5177,44 +5773,49 @@ We can easily create a Selenium `WebDriver` that integrates with `MockMvc` using .build(); } ---- - -[NOTE] -==== -This is a simple example of using `MockMvcHtmlUnitDriverBuilder`. -For more advanced usage, refer to <> ==== -This will ensure that any URL referencing `localhost` as the server will be directed to -our `MockMvc` instance without the need for a real HTTP connection. Any other URL will be -requested using a network connection as normal. This allows us to easily test the use of +NOTE: This is a simple example of using `MockMvcHtmlUnitDriverBuilder`. +For more advanced usage, see <>. + +The preceding example ensures that any URL that references `localhost` as the server is directed to +our MockMvc instance without the need for a real HTTP connection. Any other URL is +requested by using a network connection, as normal. This lets us easily test the use of CDNs. + + [[spring-mvc-test-server-htmlunit-webdriver-usage]] ====== MockMvc and WebDriver Usage -Now we can use WebDriver as we normally would, but without the need to deploy our +Now we can use WebDriver as we normally would but without the need to deploy our application to a Servlet container. For example, we can request the view to create -a message with the following. +a message with the following: +==== [source,java,indent=0] ---- CreateMessagePage page = CreateMessagePage.to(driver); ---- +==== -We can then fill out the form and submit it to create a message. +We can then fill out the form and submit it to create a message, as follows: +==== [source,java,indent=0] ---- ViewMessagePage viewMessagePage = page.createMessage(ViewMessagePage.class, expectedSummary, expectedText); ---- +==== This improves on the design of our -<> by leveraging the _Page Object -Pattern_. As we mentioned in <>, we can -use the Page Object Pattern with HtmlUnit, but it is much easier with WebDriver. Let's -take a look at our new `CreateMessagePage` implementation. +<> by leveraging the Page Object +Pattern. As we mentioned in <>, we can +use the Page Object Pattern with HtmlUnit, but it is much easier with WebDriver. +Consider the following `CreateMessagePage` implementation: +==== [source,java,indent=0] ---- public class CreateMessagePage @@ -5246,38 +5847,42 @@ take a look at our new `CreateMessagePage` implementation. } ---- -<1> The first thing you will notice is that `CreateMessagePage` extends the -`AbstractPage`. We won't go over the details of `AbstractPage`, but in summary it +<1> `CreateMessagePage` extends the +`AbstractPage`. We do not go over the details of `AbstractPage`, but, in summary, it contains common functionality for all of our pages. For example, if our application has -a navigational bar, global error messages, etc., this logic can be placed in a shared +a navigational bar, global error messages, and other features, we can place this logic in a shared location. -<2> The next thing you will notice is that we have a member variable for each of the -parts of the HTML page that we are interested in. These are of type `WebElement`. -``WebDriver``'s https://github.com/SeleniumHQ/selenium/wiki/PageFactory[PageFactory] allows -us to remove a lot of code from the HtmlUnit version of `CreateMessagePage` by +<2> We have a member variable for each of the +parts of the HTML page in which we are interested. These are of type `WebElement`. +WebDriver's https://github.com/SeleniumHQ/selenium/wiki/PageFactory[`PageFactory`] lets +us remove a lot of code from the HtmlUnit version of `CreateMessagePage` by automatically resolving each `WebElement`. The -https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/PageFactory.html#initElements-org.openqa.selenium.WebDriver-java.lang.Class-[PageFactory#initElements(WebDriver,Class)] -method will automatically resolve each `WebElement` by using the field name and looking it +https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/PageFactory.html#initElements-org.openqa.selenium.WebDriver-java.lang.Class-[`PageFactory#initElements(WebDriver,Class)`] +method automatically resolves each `WebElement` by using the field name and looking it up by the `id` or `name` of the element within the HTML page. <3> We can use the -https://github.com/SeleniumHQ/selenium/wiki/PageFactory#making-the-example-work-using-annotations[@FindBy annotation] -to override the default lookup behavior. Our example demonstrates how to use the `@FindBy` -annotation to look up our submit button using a css selector, *input[type=submit]*. +https://github.com/SeleniumHQ/selenium/wiki/PageFactory#making-the-example-work-using-annotations[`@FindBy` annotation] +to override the default lookup behavior. Our example shows how to use the `@FindBy` +annotation to look up our submit button with a css selector (*input[type=submit]*). +==== Finally, we can verify that a new message was created successfully. The following -assertions use the https://code.google.com/p/fest/[FEST assertion library]. +assertions use the https://code.google.com/p/fest/[FEST assertion library]: +==== [source,java,indent=0] ---- assertThat(viewMessagePage.getMessage()).isEqualTo(expectedMessage); assertThat(viewMessagePage.getSuccess()).isEqualTo("Successfully created a new message"); ---- +==== -We can see that our `ViewMessagePage` allows us to interact with our custom domain -model. For example, it exposes a method that returns a `Message` object. +We can see that our `ViewMessagePage` lets us interact with our custom domain +model. For example, it exposes a method that returns a `Message` object: +==== [source,java,indent=0] ---- public Message getMessage() throws ParseException { @@ -5289,11 +5894,13 @@ model. For example, it exposes a method that returns a `Message` object. return message; } ---- +==== -We can then leverage the rich domain objects in our assertions. +We can then use the rich domain objects in our assertions. -Lastly, don't forget to _close_ the `WebDriver` instance when the test is complete. +Lastly, we must not forget to close the WebDriver instance when the test is complete, as follows: +==== [source,java,indent=0] ---- @After @@ -5303,17 +5910,21 @@ Lastly, don't forget to _close_ the `WebDriver` instance when the test is comple } } ---- +==== -For additional information on using WebDriver, refer to the Selenium +For additional information on using WebDriver, see the Selenium https://github.com/SeleniumHQ/selenium/wiki/Getting-Started[WebDriver documentation]. + + [[spring-mvc-test-server-htmlunit-webdriver-advanced-builder]] -====== Advanced MockMvcHtmlUnitDriverBuilder +====== Advanced `MockMvcHtmlUnitDriverBuilder` In the examples so far, we have used `MockMvcHtmlUnitDriverBuilder` in the simplest way -possible, by building a `WebDriver` based on the `WebApplicationContext` loaded for us by -the Spring TestContext Framework. This approach is repeated here. +possible, by building a WebDriver based on the `WebApplicationContext` loaded for us by +the Spring TestContext Framework. This approach is repeated here, as follows: +==== [source,java,indent=0] ---- @Autowired @@ -5328,9 +5939,11 @@ the Spring TestContext Framework. This approach is repeated here. .build(); } ---- +==== -We can also specify additional configuration options. +We can also specify additional configuration options, as follows: +==== [source,java,indent=0] ---- WebDriver driver; @@ -5348,10 +5961,12 @@ We can also specify additional configuration options. .build(); } ---- +==== -As an alternative, we can perform the exact same setup by configuring the `MockMvc` -instance separately and supplying it to the `MockMvcHtmlUnitDriverBuilder` as follows. +As an alternative, we can perform the exact same setup by configuring the MockMvc +instance separately and supplying it to the `MockMvcHtmlUnitDriverBuilder`, as follows: +==== [source,java,indent=0] ---- MockMvc mockMvc = MockMvcBuilders @@ -5368,21 +5983,23 @@ instance separately and supplying it to the `MockMvcHtmlUnitDriverBuilder` as fo .useMockMvcForHosts("example.com","example.org") .build(); ---- - -This is more verbose, but by building the `WebDriver` with a `MockMvc` instance we have -the full power of `MockMvc` at our fingertips. - -[TIP] ==== -For additional information on creating a `MockMvc` instance refer to + +This is more verbose, but, by building the WebDriver with a MockMvc instance, we have +the full power of MockMvc at our fingertips. + +TIP: For additional information on creating a MockMvc instance, see <>. -==== + + [[spring-mvc-test-server-htmlunit-geb]] ===== MockMvc and Geb -In the previous section, we saw how to use `MockMvc` with `WebDriver`. In this section, -we will use http://www.gebish.org/[Geb] to make our tests even Groovy-er. +In the previous section, we saw how to use MockMvc with WebDriver. In this section, +we use http://www.gebish.org/[Geb] to make our tests even Groovy-er. + + [[spring-mvc-test-server-htmlunit-geb-why]] ====== Why Geb and MockMvc? @@ -5392,12 +6009,15 @@ Geb is backed by WebDriver, so it offers many of the WebDriver. However, Geb makes things even easier by taking care of some of the boilerplate code for us. + + [[spring-mvc-test-server-htmlunit-geb-setup]] ====== MockMvc and Geb Setup -We can easily initialize a Geb `Browser` with a Selenium `WebDriver` that uses `MockMvc` -as follows. +We can easily initialize a Geb `Browser` with a Selenium WebDriver that uses MockMvc, +as follows: +==== [source,groovy] ---- def setup() { @@ -5406,32 +6026,35 @@ def setup() { .build() } ---- - -[NOTE] -==== -This is a simple example of using `MockMvcHtmlUnitDriverBuilder`. -For more advanced usage, refer to <> ==== -This will ensure that any URL referencing `localhost` as the server will be directed to -our `MockMvc` instance without the need for a real HTTP connection. Any other URL will be -requested using a network connection as normal. This allows us to easily test the use of +NOTE: This is a simple example of using `MockMvcHtmlUnitDriverBuilder`. +For more advanced usage, see <>. + +This ensures that any URL referencing `localhost` as the server is directed to +our MockMvc instance without the need for a real HTTP connection. Any other URL is +requested by using a network connection as normal. This lets us easily test the use of CDNs. + + [[spring-mvc-test-server-htmlunit-geb-usage]] ====== MockMvc and Geb Usage -Now we can use Geb as we normally would, but without the need to deploy our +Now we can use Geb as we normally would but without the need to deploy our application to a Servlet container. For example, we can request the view to create a message with the following: +==== [source,groovy] ---- to CreateMessagePage ---- +==== -We can then fill out the form and submit it to create a message. +We can then fill out the form and submit it to create a message, as follows: +==== [source,groovy] ---- when: @@ -5439,17 +6062,19 @@ form.summary = expectedSummary form.text = expectedMessage submit.click(ViewMessagePage) ---- +==== -Any unrecognized method calls or property accesses/references that are not found will be +Any unrecognized method calls or property accesses or references that are not found are forwarded to the current page object. This removes a lot of the boilerplate code we needed when using WebDriver directly. As with direct WebDriver usage, this improves on the design of our -<> by leveraging the _Page Object -Pattern_. As mentioned previously, we can use the Page Object Pattern with HtmlUnit and -WebDriver, but it is even easier with Geb. Let's take a look at our new Groovy-based -`CreateMessagePage` implementation. +<> by using the Page Object +Pattern. As mentioned previously, we can use the Page Object Pattern with HtmlUnit and +WebDriver, but it is even easier with Geb. Consider our new Groovy-based +`CreateMessagePage` implementation: +==== [source,groovy] ---- class CreateMessagePage extends Page { @@ -5462,41 +6087,44 @@ class CreateMessagePage extends Page { } } ---- +==== -The first thing you will notice is that our `CreateMessagePage` extends `Page`. We won't -go over the details of `Page`, but in summary it contains common functionality for all of -our pages. The next thing you will notice is that we define a URL in which this page can -be found. This allows us to navigate to the page as follows. +Our `CreateMessagePage` extends `Page`. We do not +go over the details of `Page`, but, in summary, it contains common functionality for all of +our pages. We define a URL in which this page can +be found. This lets us navigate to the page, as follows: +==== [source,groovy] ---- to CreateMessagePage ---- +==== We also have an `at` closure that determines if we are at the specified page. It should return `true` if we are on the correct page. This is why we can assert that we are on the correct -page as follows. +page, as follows: +==== [source,groovy] ---- then: at CreateMessagePage errors.contains('This field is required.') ---- - -[NOTE] ==== -We use an assertion in the closure, so that we can determine where things went wrong if + +NOTE: We use an assertion in the closure so that we can determine where things went wrong if we were at the wrong page. -==== -Next we create a `content` closure that specifies all the areas of interest within the page. +Next, we create a `content` closure that specifies all the areas of interest within the page. We can use a http://www.gebish.org/manual/current/#the-jquery-ish-navigator-api[jQuery-ish Navigator API] -to select the content we are interested in. +to select the content in which we are interested. -Finally, we can verify that a new message was created successfully. +Finally, we can verify that a new message was created successfully, as follows: +==== [source,groovy] ---- then: @@ -5507,19 +6135,22 @@ date summary == expectedSummary message == expectedMessage ---- +==== -For further details on how to get the most out of Geb, consult +For further details on how to get the most out of Geb, see http://www.gebish.org/manual/current/[The Book of Geb] user's manual. + [[spring-mvc-test-client]] ==== Client-Side REST Tests -Client-side tests can be used to test code that internally uses the `RestTemplate`. -The idea is to declare expected requests and to provide "stub" responses so that -you can focus on testing the code in isolation, i.e. without running a server. -Here is an example: +You can use client-side tests to test code that internally uses the `RestTemplate`. +The idea is to declare expected requests and to provide "`stub`" responses so that +you can focus on testing the code in isolation (that is, without running a server). +The following example shows how to do so: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -5532,57 +6163,63 @@ Here is an example: 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 request to "/greeting" and want to return a 200 response with -"text/plain" content. We could define as additional expected requests and stub responses as -needed. When expected requests and stub responses are defined, the `RestTemplate` can be -used in client-side code as usual. At the end of testing `mockServer.verify()` can be +In the preceding 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 request to `/greeting` and want to return a 200 response with +`text/plain` content. We can define additional expected requests and stub responses as +needed. When we define expected requests and stub responses, the `RestTemplate` can be +used in client-side code as usual. At the end of testing, `mockServer.verify()` can be used to verify that all expectations have been satisfied. -By default requests are expected in the order in which expectations were declared. -You can set the `ignoreExpectOrder` option when building the server in which case +By default, requests are expected in the order in which expectations were declared. +You can set the `ignoreExpectOrder` option when building the server, in which case all expectations are checked (in order) to find a match for a given request. That -means requests are allowed to come in any order. Here is an example: +means requests are allowed to come in any order. The following example uses `ignoreExpectOrder`: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- server = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build(); ---- +==== -Even with unordered requests by default each request is allowed to execute once only. +Even with unordered requests by default, each request is allowed to execute once only. The `expect` method provides an overloaded variant that accepts an `ExpectedCount` -argument that specifies a count range, e.g. `once`, `manyTimes`, `max`, `min`, -`between`, and so on. Here is an example: +argument that specifies a count range (for example, `once`, `manyTimes`, `max`, `min`, +`between`, and so on). The following example uses `times`: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- RestTemplate restTemplate = new RestTemplate(); MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build(); - mockServer.expect(times(2), requestTo("/foo")).andRespond(withSuccess()); - mockServer.expect(times(3), requestTo("/bar")).andRespond(withSuccess()); + mockServer.expect(times(2), requestTo("/something")).andRespond(withSuccess()); + mockServer.expect(times(3), requestTo("/somewhere")).andRespond(withSuccess()); // ... mockServer.verify(); ---- +==== -Note that when `ignoreExpectOrder` is not set (the default), and therefore requests -are expected in order of declaration, then that order only applies to the first of -any expected request. For example if "/foo" is expected 2 times followed by "/bar" -3 times, then there should be a request to "/foo" before there is a request to "/bar" -but aside from that subsequent "/foo" and "/bar" requests can come at any time. +Note that, when `ignoreExpectOrder` is not set (the default), and, therefore, requests +are expected in order of declaration, then that order applies only to the first of +any expected request. For example if "/something" is expected two times followed by "/somewhere" +three times, then there should be a request to "/something" before there is a request to "/somewhere", +but, aside from that subsequent "/something" and "/somewhere", requests can come at any time. -As an alternative to all of the above the client-side test support also provides a -`ClientHttpRequestFactory` implementation that can be configured into a `RestTemplate` -to bind it to a `MockMvc` instance. That allows processing requests using actual -server-side logic but without running a server. Here is an example: +As an alternative to all of the above, the client-side test support also provides a +`ClientHttpRequestFactory` implementation that you can configure into a `RestTemplate` +to bind it to a MockMvc instance. That allows processing requests using actual +server-side logic but without running a server. The following example shows how to do so: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- @@ -5591,18 +6228,21 @@ server-side logic but without running a server. Here is an example: // Test code that uses the above RestTemplate ... ---- +==== [[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__. +As with server-side tests, the fluent API for client-side tests requires a few +static imports. Those are easy to find by searching for `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. +static method name. Other IDEs (such IntelliJ) may not require any additional +configuration. Check for the support for code completion on static members. + + [[spring-mvc-test-client-resources]] ===== Further Examples of Client-side REST Tests @@ -5621,27 +6261,28 @@ include::testing-webtestclient.adoc[leveloffset=+2] === 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 4 environment. Most test functionality -is included in the `AbstractClinicTests`, for which a partial listing is shown below: +https://github.com/spring-projects/spring-petclinic[GitHub], shows several features +of the Spring TestContext Framework in a JUnit 4 environment. Most test functionality +is included in the `AbstractClinicTests`, for which a partial listing follows: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- import static org.junit.Assert.assertEquals; // import ... - **@ContextConfiguration** - public abstract class AbstractClinicTests **extends AbstractTransactionalJUnit4SpringContextTests** { + @ContextConfiguration <1> + public abstract class AbstractClinicTests extends AbstractTransactionalJUnit4SpringContextTests { <2> - **@Autowired** + @Autowired <3> protected Clinic clinic; @Test public void getVets() { Collection vets = this.clinic.getVets(); assertEquals("JDBC query must show the same number of vets", - **super.countRowsInTable("VETS")**, vets.size()); + super.countRowsInTable("VETS"), vets.size()); <4> Vet v1 = EntityUtils.getById(vets, Vet.class, 2); assertEquals("Leary", v1.getLastName()); assertEquals(1, v1.getNrOfSpecialties()); @@ -5653,94 +6294,98 @@ is included in the `AbstractClinicTests`, for which a partial listing is shown b } ---- -Notes: +<1> Load the application context from the default location: `AbstractClinicTests-context.xml`. +<2> This test case extends the `AbstractTransactionalJUnit4SpringContextTests` class, from +which it inherits configuration for Dependency Injection (through the +`DependencyInjectionTestExecutionListener`) and transactional behavior (through the +`TransactionalTestExecutionListener`). +<3> The `clinic` instance variable (the application object being tested) is set by +Dependency Injection through `@Autowired` semantics. +<4> The `getVets()` method shows 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. +==== -* 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. +Like many integration tests that use a database, most of the tests in +`AbstractClinicTests` depend on a minimum amount of data already being in the database before +the test cases run. Alternatively, you can 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 +`AbstractClinicTests` class has 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 +of code. We need only 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 +specific resource locations, the Spring TestContext Framework loads an application +context from all the beans defined in `AbstractClinicTests-context.xml` (that is, the inherited locations) and `HibernateClinicTests-context.xml`, with `HibernateClinicTests-context.xml` possibly overriding beans defined in `AbstractClinicTests-context.xml`. +The following listing shows the definition of the `HibernateClinicTests` class: +==== [source,java,indent=0] [subs="verbatim,quotes"] ---- - **@ContextConfiguration** + @ContextConfiguration <1> public class HibernateClinicTests extends AbstractClinicTests { } ---- +<1> Load the application context from the default location: `AbstractClinicTests-context.xml`. +==== 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. +class for all application-specific integration tests. Such a base class can also add +useful instance variables (populated by Dependency Injection, naturally), such as a +`SessionFactory` in the case of an application that uses 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 +deploying to a full-blown application server, you probably use its connection pool +(available through JNDI) and JTA implementation. Thus, in production, you can use a `JndiObjectFactoryBean` or `` 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 +`JtaTransactionManager`. JNDI and JTA are not available in out-of-container +integration tests, so you should use a combination such as 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 +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 +addition, we recommend that you 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: +See the following resources for more information about testing: -* http://www.junit.org/[JUnit]: "__A programmer-oriented testing framework for Java__". +* 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://joel-costigliola.github.io/assertj/[AssertJ]: "__Fluent assertions for Java__" - including support for Java 8 lambdas, streams, etc. + for annotations, test groups, data-driven testing, distributed testing, and other features. +* http://joel-costigliola.github.io/assertj/[AssertJ]: "`Fluent assertions for Java`", + including support for Java 8 lambdas, streams, and other features. * http://en.wikipedia.org/wiki/Mock_Object[Mock Objects]: Article in Wikipedia. * 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://mockito.org/[Mockito]: Java mock library based on the - http://xunitpatterns.com/Test%20Spy.html[test spy] pattern. -* http://www.easymock.org/[EasyMock]: Java library "__that provides Mock Objects for + http://xunitpatterns.com/Test%20Spy.html[Test Spy] pattern. +* 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. + 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://dbunit.sourceforge.net/[DbUnit]: JUnit extension (also usable with Ant and - Maven) targeted for database-driven projects that, among other things, puts your + Maven) that is targeted at database-driven projects and, among other things, puts your database into a known state between test runs. * http://grinder.sourceforge.net/[The Grinder]: Java load testing framework.