(window.webpackJsonp=window.webpackJsonp||[]).push([[99],{528:function(e,t,n){"use strict";n.r(t);var a=n(56),s=Object(a.a)({},(function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("ContentSlotsDistributor",{attrs:{"slot-key":e.$parent.slotKey}},[n("h1",{attrs:{id:"testing"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#testing"}},[e._v("#")]),e._v(" Testing")]),e._v(" "),n("p",[e._v("This chapter covers Spring’s support for integration testing and best practices for unit\ntesting. The Spring team advocates test-driven development (TDD). The Spring team has\nfound that the correct use of inversion of control (IoC) certainly does make both unit\nand integration testing easier (in that the presence of setter methods and appropriate\nconstructors on classes makes them easier to wire together in a test without having to\nset up service locator registries and similar structures).")]),e._v(" "),n("h2",{attrs:{id:"_1-introduction-to-spring-testing"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_1-introduction-to-spring-testing"}},[e._v("#")]),e._v(" 1. Introduction to Spring Testing")]),e._v(" "),n("p",[e._v("Testing is an integral part of enterprise software development. This chapter focuses on\nthe value added by the IoC principle to "),n("a",{attrs:{href:"#unit-testing"}},[e._v("unit testing")]),e._v(" and on the benefits\nof the Spring Framework’s support for "),n("a",{attrs:{href:"#integration-testing"}},[e._v("integration testing")]),e._v(". (A\nthorough treatment of testing in the enterprise is beyond the scope of this reference\nmanual.)")]),e._v(" "),n("h2",{attrs:{id:"_2-unit-testing"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-unit-testing"}},[e._v("#")]),e._v(" 2. Unit Testing")]),e._v(" "),n("p",[e._v("Dependency injection should make your code less dependent on the container than it would\nbe with traditional Java EE development. The POJOs that make up your application should\nbe testable in JUnit or TestNG tests, with objects instantiated by using the "),n("code",[e._v("new")]),e._v("operator, without Spring or any other container. You can use "),n("a",{attrs:{href:"#mock-objects"}},[e._v("mock objects")]),e._v("(in conjunction with other valuable testing techniques) to test your code in isolation.\nIf you follow the architecture recommendations for Spring, the resulting clean layering\nand componentization of your codebase facilitate easier unit testing. For example,\nyou can test service layer objects by stubbing or mocking DAO or repository interfaces,\nwithout needing to access persistent data while running unit tests.")]),e._v(" "),n("p",[e._v("True unit tests typically run extremely quickly, as there is no runtime infrastructure to\nset up. Emphasizing true unit tests as part of your development methodology can boost\nyour productivity. You may not need this section of the testing chapter to help you write\neffective unit tests for your IoC-based applications. For certain unit testing scenarios,\nhowever, the Spring Framework provides mock objects and testing support classes, which\nare described in this chapter.")]),e._v(" "),n("h3",{attrs:{id:"_2-1-mock-objects"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-1-mock-objects"}},[e._v("#")]),e._v(" 2.1. Mock Objects")]),e._v(" "),n("p",[e._v("Spring includes a number of packages dedicated to mocking:")]),e._v(" "),n("ul",[n("li",[n("p",[n("a",{attrs:{href:"#mock-objects-env"}},[e._v("Environment")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#mock-objects-jndi"}},[e._v("JNDI")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#mock-objects-servlet"}},[e._v("Servlet API")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#mock-objects-web-reactive"}},[e._v("Spring Web Reactive")])])])]),e._v(" "),n("h4",{attrs:{id:"_2-1-1-environment"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-1-1-environment"}},[e._v("#")]),e._v(" 2.1.1. Environment")]),e._v(" "),n("p",[e._v("The "),n("code",[e._v("org.springframework.mock.env")]),e._v(" package contains mock implementations of the"),n("code",[e._v("Environment")]),e._v(" and "),n("code",[e._v("PropertySource")]),e._v(" abstractions (see"),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#beans-definition-profiles"}},[e._v("Bean Definition Profiles")]),e._v("and "),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#beans-property-source-abstraction"}},[n("code",[e._v("PropertySource")]),e._v(" Abstraction")]),e._v(")."),n("code",[e._v("MockEnvironment")]),e._v(" and "),n("code",[e._v("MockPropertySource")]),e._v(" are useful for developing\nout-of-container tests for code that depends on environment-specific properties.")],1),e._v(" "),n("h4",{attrs:{id:"_2-1-2-jndi"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-1-2-jndi"}},[e._v("#")]),e._v(" 2.1.2. JNDI")]),e._v(" "),n("p",[e._v("The "),n("code",[e._v("org.springframework.mock.jndi")]),e._v(" package contains a partial implementation of the JNDI\nSPI, which you can use to set up a simple JNDI environment for test suites or stand-alone\napplications. If, for example, JDBC "),n("code",[e._v("DataSource")]),e._v(" instances get bound to the same JNDI\nnames in test code as they do in a Java EE container, you can reuse both application code\nand configuration in testing scenarios without modification.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("The mock JNDI support in the "),n("code",[e._v("org.springframework.mock.jndi")]),e._v(" package is"),n("br"),e._v("officially deprecated as of Spring Framework 5.2 in favor of complete solutions from third"),n("br"),e._v("parties such as "),n("a",{attrs:{href:"https://github.com/h-thurow/Simple-JNDI",target:"_blank",rel:"noopener noreferrer"}},[e._v("Simple-JNDI"),n("OutboundLink")],1),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h4",{attrs:{id:"_2-1-3-servlet-api"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-1-3-servlet-api"}},[e._v("#")]),e._v(" 2.1.3. Servlet API")]),e._v(" "),n("p",[e._v("The "),n("code",[e._v("org.springframework.mock.web")]),e._v(" package contains a comprehensive set of Servlet API\nmock objects that are useful for testing web contexts, controllers, and filters. These\nmock objects are targeted at usage with Spring’s Web MVC framework and are generally more\nconvenient to use than dynamic mock objects (such as "),n("a",{attrs:{href:"http://easymock.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("EasyMock"),n("OutboundLink")],1),e._v(")\nor alternative Servlet API mock objects (such as "),n("a",{attrs:{href:"http://www.mockobjects.com",target:"_blank",rel:"noopener noreferrer"}},[e._v("MockObjects"),n("OutboundLink")],1),e._v(").")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Since Spring Framework 5.0, the mock objects in "),n("code",[e._v("org.springframework.mock.web")]),e._v(" are"),n("br"),e._v("based on the Servlet 4.0 API.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("The Spring MVC Test framework builds on the mock Servlet API objects to provide an\nintegration testing framework for Spring MVC. See "),n("a",{attrs:{href:"#spring-mvc-test-framework"}},[e._v("MockMvc")]),e._v(".")]),e._v(" "),n("h4",{attrs:{id:"_2-1-4-spring-web-reactive"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-1-4-spring-web-reactive"}},[e._v("#")]),e._v(" 2.1.4. Spring Web Reactive")]),e._v(" "),n("p",[e._v("The "),n("code",[e._v("org.springframework.mock.http.server.reactive")]),e._v(" package contains mock implementations\nof "),n("code",[e._v("ServerHttpRequest")]),e._v(" and "),n("code",[e._v("ServerHttpResponse")]),e._v(" for use in WebFlux applications. The"),n("code",[e._v("org.springframework.mock.web.server")]),e._v(" package contains a mock "),n("code",[e._v("ServerWebExchange")]),e._v(" that\ndepends on those mock request and response objects.")]),e._v(" "),n("p",[e._v("Both "),n("code",[e._v("MockServerHttpRequest")]),e._v(" and "),n("code",[e._v("MockServerHttpResponse")]),e._v(" extend from the same abstract\nbase classes as server-specific implementations and share behavior with them. For\nexample, a mock request is immutable once created, but you can use the "),n("code",[e._v("mutate()")]),e._v(" method\nfrom "),n("code",[e._v("ServerHttpRequest")]),e._v(" to create a modified instance.")]),e._v(" "),n("p",[e._v("In order for the mock response to properly implement the write contract and return a\nwrite completion handle (that is, "),n("code",[e._v("Mono")]),e._v("), it by default uses a "),n("code",[e._v("Flux")]),e._v(" with"),n("code",[e._v("cache().then()")]),e._v(", which buffers the data and makes it available for assertions in tests.\nApplications can set a custom write function (for example, to test an infinite stream).")]),e._v(" "),n("p",[e._v("The "),n("a",{attrs:{href:"#webtestclient"}},[e._v("WebTestClient")]),e._v(" builds on the mock request and response to provide support for\ntesting WebFlux applications without an HTTP server. The client can also be used for\nend-to-end tests with a running server.")]),e._v(" "),n("h3",{attrs:{id:"_2-2-unit-testing-support-classes"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-2-unit-testing-support-classes"}},[e._v("#")]),e._v(" 2.2. Unit Testing Support Classes")]),e._v(" "),n("p",[e._v("Spring includes a number of classes that can help with unit testing. They fall into two\ncategories:")]),e._v(" "),n("ul",[n("li",[n("p",[n("a",{attrs:{href:"#unit-testing-utilities"}},[e._v("General Testing Utilities")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#unit-testing-spring-mvc"}},[e._v("Spring MVC Testing Utilities")])])])]),e._v(" "),n("h4",{attrs:{id:"_2-2-1-general-testing-utilities"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-2-1-general-testing-utilities"}},[e._v("#")]),e._v(" 2.2.1. General Testing Utilities")]),e._v(" "),n("p",[e._v("The "),n("code",[e._v("org.springframework.test.util")]),e._v(" package contains several general purpose utilities\nfor use in unit and integration testing.")]),e._v(" "),n("p",[n("code",[e._v("ReflectionTestUtils")]),e._v(" is a collection of reflection-based utility methods. You can use\nthese methods in testing scenarios where you need to change the value of a constant, set\na non-"),n("code",[e._v("public")]),e._v(" field, invoke a non-"),n("code",[e._v("public")]),e._v(" setter method, or invoke a non-"),n("code",[e._v("public")]),e._v("configuration or lifecycle callback method when testing application code for use cases\nsuch as the following:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("ORM frameworks (such as JPA and Hibernate) that condone "),n("code",[e._v("private")]),e._v(" or "),n("code",[e._v("protected")]),e._v(" field\naccess as opposed to "),n("code",[e._v("public")]),e._v(" setter methods for properties in a domain entity.")])]),e._v(" "),n("li",[n("p",[e._v("Spring’s support for annotations (such as "),n("code",[e._v("@Autowired")]),e._v(", "),n("code",[e._v("@Inject")]),e._v(", and "),n("code",[e._v("@Resource")]),e._v("),\nthat provide dependency injection for "),n("code",[e._v("private")]),e._v(" or "),n("code",[e._v("protected")]),e._v(" fields, setter methods,\nand configuration methods.")])]),e._v(" "),n("li",[n("p",[e._v("Use of annotations such as "),n("code",[e._v("@PostConstruct")]),e._v(" and "),n("code",[e._v("@PreDestroy")]),e._v(" for lifecycle callback\nmethods.")])])]),e._v(" "),n("p",[n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/util/AopTestUtils.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("AopTestUtils")]),n("OutboundLink")],1),e._v(" is a collection of\nAOP-related utility methods. You can use these methods to obtain a reference to the\nunderlying target object hidden behind one or more Spring proxies. For example, if you\nhave configured a bean as a dynamic mock by using a library such as EasyMock or Mockito,\nand the mock is wrapped in a Spring proxy, you may need direct access to the underlying\nmock to configure expectations on it and perform verifications. For Spring’s core AOP\nutilities, see "),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/aop/support/AopUtils.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("AopUtils")]),n("OutboundLink")],1),e._v(" and"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/aop/framework/AopProxyUtils.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("AopProxyUtils")]),n("OutboundLink")],1),e._v(".")]),e._v(" "),n("h4",{attrs:{id:"_2-2-2-spring-mvc-testing-utilities"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-2-2-spring-mvc-testing-utilities"}},[e._v("#")]),e._v(" 2.2.2. Spring MVC Testing Utilities")]),e._v(" "),n("p",[e._v("The "),n("code",[e._v("org.springframework.test.web")]),e._v(" package contains"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/web/ModelAndViewAssert.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("ModelAndViewAssert")]),n("OutboundLink")],1),e._v(", which you\ncan use in combination with JUnit, TestNG, or any other testing framework for unit tests\nthat deal with Spring MVC "),n("code",[e._v("ModelAndView")]),e._v(" objects.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Unit testing Spring MVC Controllers"),n("br"),n("br"),e._v("To unit test your Spring MVC "),n("code",[e._v("Controller")]),e._v(" classes as POJOs, use "),n("code",[e._v("ModelAndViewAssert")]),e._v("combined with "),n("code",[e._v("MockHttpServletRequest")]),e._v(", "),n("code",[e._v("MockHttpSession")]),e._v(", and so on from Spring’s"),n("a",{attrs:{href:"#mock-objects-servlet"}},[e._v("Servlet API mocks")]),e._v(". For thorough integration testing of your"),n("br"),e._v("Spring MVC and REST "),n("code",[e._v("Controller")]),e._v(" classes in conjunction with your "),n("code",[e._v("WebApplicationContext")]),e._v("configuration for Spring MVC, use the"),n("a",{attrs:{href:"#spring-mvc-test-framework"}},[e._v("Spring MVC Test Framework")]),e._v(" instead.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h2",{attrs:{id:"_3-integration-testing"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-integration-testing"}},[e._v("#")]),e._v(" 3. Integration Testing")]),e._v(" "),n("p",[e._v("This section (most of the rest of this chapter) covers integration testing for Spring\napplications. It includes the following topics:")]),e._v(" "),n("ul",[n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-overview"}},[e._v("Overview")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-goals"}},[e._v("Goals of Integration Testing")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-support-jdbc"}},[e._v("JDBC Testing Support")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations"}},[e._v("Annotations")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-framework"}},[e._v("Spring TestContext Framework")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-mvc-test-framework"}},[e._v("MockMvc")])])])]),e._v(" "),n("h3",{attrs:{id:"_3-1-overview"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-1-overview"}},[e._v("#")]),e._v(" 3.1. Overview")]),e._v(" "),n("p",[e._v("It is important to be able to perform some integration testing without requiring\ndeployment to your application server or connecting to other enterprise infrastructure.\nDoing so lets you test things such as:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("The correct wiring of your Spring IoC container contexts.")])]),e._v(" "),n("li",[n("p",[e._v("Data access using JDBC or an ORM tool. This can include such things as the correctness\nof SQL statements, Hibernate queries, JPA entity mappings, and so forth.")])])]),e._v(" "),n("p",[e._v("The Spring Framework provides first-class support for integration testing in the"),n("code",[e._v("spring-test")]),e._v(" module. The name of the actual JAR file might include the release version\nand might also be in the long "),n("code",[e._v("org.springframework.test")]),e._v(" form, depending on where you get\nit from (see the "),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#dependency-management"}},[e._v("section on Dependency Management")]),e._v("for an explanation). This library includes the "),n("code",[e._v("org.springframework.test")]),e._v(" package, which\ncontains valuable classes for integration testing with a Spring container. This testing\ndoes not rely on an application server or other deployment environment. Such tests are\nslower to run than unit tests but much faster than the equivalent Selenium tests or\nremote tests that rely on deployment to an application server.")],1),e._v(" "),n("p",[e._v("Unit and integration testing support is provided in the form of the annotation-driven"),n("a",{attrs:{href:"#testcontext-framework"}},[e._v("Spring TestContext Framework")]),e._v(". The TestContext framework is\nagnostic of the actual testing framework in use, which allows instrumentation of tests\nin various environments, including JUnit, TestNG, and others.")]),e._v(" "),n("h3",{attrs:{id:"_3-2-goals-of-integration-testing"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-2-goals-of-integration-testing"}},[e._v("#")]),e._v(" 3.2. Goals of Integration Testing")]),e._v(" "),n("p",[e._v("Spring’s integration testing support has the following primary goals:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("To manage "),n("a",{attrs:{href:"#testing-ctx-management"}},[e._v("Spring IoC container caching")]),e._v(" between tests.")])]),e._v(" "),n("li",[n("p",[e._v("To provide "),n("a",{attrs:{href:"#testing-fixture-di"}},[e._v("Dependency Injection of test fixture instances")]),e._v(".")])]),e._v(" "),n("li",[n("p",[e._v("To provide "),n("a",{attrs:{href:"#testing-tx"}},[e._v("transaction management")]),e._v(" appropriate to integration testing.")])]),e._v(" "),n("li",[n("p",[e._v("To supply "),n("a",{attrs:{href:"#testing-support-classes"}},[e._v("Spring-specific base classes")]),e._v(" that assist\ndevelopers in writing integration tests.")])])]),e._v(" "),n("p",[e._v("The next few sections describe each goal and provide links to implementation and\nconfiguration details.")]),e._v(" "),n("h4",{attrs:{id:"_3-2-1-context-management-and-caching"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-2-1-context-management-and-caching"}},[e._v("#")]),e._v(" 3.2.1. Context Management and Caching")]),e._v(" "),n("p",[e._v("The Spring TestContext Framework provides consistent loading of Spring"),n("code",[e._v("ApplicationContext")]),e._v(" instances and "),n("code",[e._v("WebApplicationContext")]),e._v(" instances as well as caching\nof those contexts. Support for the caching of loaded contexts is important, because\nstartup time can become an issue — not because of the overhead of Spring itself, but\nbecause the objects instantiated by the Spring container take time to instantiate. For\nexample, a project with 50 to 100 Hibernate mapping files might take 10 to 20 seconds to\nload the mapping files, and incurring that cost before running every test in every test\nfixture leads to slower overall test runs that reduce developer productivity.")]),e._v(" "),n("p",[e._v("Test classes typically declare either an array of resource locations for XML or Groovy\nconfiguration metadata — often in the classpath — or an array of component classes that\nis used to configure the application. These locations or classes are the same as or\nsimilar to those specified in "),n("code",[e._v("web.xml")]),e._v(" or other configuration files for production\ndeployments.")]),e._v(" "),n("p",[e._v("By default, once loaded, the configured "),n("code",[e._v("ApplicationContext")]),e._v(" is reused for each test.\nThus, the setup cost is incurred only once per test suite, and subsequent test execution\nis much faster. In this context, the term “test suite” means all tests run in the same\nJVM — for example, all tests run from an Ant, Maven, or Gradle build for a given project\nor module. In the unlikely case that a test corrupts the application context and requires\nreloading (for example, by modifying a bean definition or the state of an application\nobject) the TestContext framework can be configured to reload the configuration and\nrebuild the application context before executing the next test.")]),e._v(" "),n("p",[e._v("See "),n("a",{attrs:{href:"#testcontext-ctx-management"}},[e._v("Context Management")]),e._v(" and "),n("a",{attrs:{href:"#testcontext-ctx-management-caching"}},[e._v("Context Caching")]),e._v(" with the\nTestContext framework.")]),e._v(" "),n("h4",{attrs:{id:"_3-2-2-dependency-injection-of-test-fixtures"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-2-2-dependency-injection-of-test-fixtures"}},[e._v("#")]),e._v(" 3.2.2. Dependency Injection of Test Fixtures")]),e._v(" "),n("p",[e._v("When the TestContext framework loads your application context, it can optionally\nconfigure instances of your test classes by using Dependency Injection. This provides a\nconvenient mechanism for setting up test fixtures by using preconfigured beans from your\napplication context. A strong benefit here is that you can reuse application contexts\nacross various testing scenarios (for example, for configuring Spring-managed object\ngraphs, transactional proxies, "),n("code",[e._v("DataSource")]),e._v(" instances, and others), thus avoiding the\nneed to duplicate complex test fixture setup for individual test cases.")]),e._v(" "),n("p",[e._v("As an example, consider a scenario where we have a class ("),n("code",[e._v("HibernateTitleRepository")]),e._v(")\nthat implements data access logic for a "),n("code",[e._v("Title")]),e._v(" domain entity. We want to write\nintegration tests that test the following areas:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("The Spring configuration: Basically, is everything related to the configuration of the"),n("code",[e._v("HibernateTitleRepository")]),e._v(" bean correct and present?")])]),e._v(" "),n("li",[n("p",[e._v("The Hibernate mapping file configuration: Is everything mapped correctly and are the\ncorrect lazy-loading settings in place?")])]),e._v(" "),n("li",[n("p",[e._v("The logic of the "),n("code",[e._v("HibernateTitleRepository")]),e._v(": Does the configured instance of this class\nperform as anticipated?")])])]),e._v(" "),n("p",[e._v("See dependency injection of test fixtures with the"),n("a",{attrs:{href:"#testcontext-fixture-di"}},[e._v("TestContext framework")]),e._v(".")]),e._v(" "),n("h4",{attrs:{id:"_3-2-3-transaction-management"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-2-3-transaction-management"}},[e._v("#")]),e._v(" 3.2.3. Transaction Management")]),e._v(" "),n("p",[e._v("One common issue in tests that access a real database is their effect on the state of the\npersistence store. Even when you use a development database, changes to the state may\naffect future tests. Also, many operations — such as inserting or modifying persistent\ndata — cannot be performed (or verified) outside of a transaction.")]),e._v(" "),n("p",[e._v("The TestContext framework addresses this issue. By default, the framework creates and\nrolls back a transaction for each test. You can write code that can assume the existence\nof a transaction. If you call transactionally proxied objects in your tests, they behave\ncorrectly, according to their configured transactional semantics. In addition, if a test\nmethod deletes the contents of selected tables while running within the transaction\nmanaged for the test, the transaction rolls back by default, and the database returns to\nits state prior to execution of the test. Transactional support is provided to a test by\nusing a "),n("code",[e._v("PlatformTransactionManager")]),e._v(" bean defined in the test’s application context.")]),e._v(" "),n("p",[e._v("If you want a transaction to commit (unusual, but occasionally useful when you want a\nparticular test to populate or modify the database), you can tell the TestContext\nframework to cause the transaction to commit instead of roll back by using the"),n("a",{attrs:{href:"#integration-testing-annotations"}},[n("code",[e._v("@Commit")])]),e._v(" annotation.")]),e._v(" "),n("p",[e._v("See transaction management with the "),n("a",{attrs:{href:"#testcontext-tx"}},[e._v("TestContext framework")]),e._v(".")]),e._v(" "),n("h4",{attrs:{id:"_3-2-4-support-classes-for-integration-testing"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-2-4-support-classes-for-integration-testing"}},[e._v("#")]),e._v(" 3.2.4. Support Classes for Integration Testing")]),e._v(" "),n("p",[e._v("The Spring TestContext Framework provides several "),n("code",[e._v("abstract")]),e._v(" support classes that\nsimplify the writing of integration tests. These base test classes provide well-defined\nhooks into the testing framework as well as convenient instance variables and methods,\nwhich let you access:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("The "),n("code",[e._v("ApplicationContext")]),e._v(", for performing explicit bean lookups or testing the state of\nthe context as a whole.")])]),e._v(" "),n("li",[n("p",[e._v("A "),n("code",[e._v("JdbcTemplate")]),e._v(", for executing SQL statements to query the database. You can use such\nqueries to confirm database state both before and after execution of database-related\napplication code, and Spring ensures that such queries run in the scope of the same\ntransaction as the application code. When used in conjunction with an ORM tool, be sure\nto avoid "),n("a",{attrs:{href:"#testcontext-tx-false-positives"}},[e._v("false positives")]),e._v(".")])])]),e._v(" "),n("p",[e._v("In addition, you may want to create your own custom, application-wide superclass with\ninstance variables and methods specific to your project.")]),e._v(" "),n("p",[e._v("See support classes for the "),n("a",{attrs:{href:"#testcontext-support-classes"}},[e._v("TestContext framework")]),e._v(".")]),e._v(" "),n("h3",{attrs:{id:"_3-3-jdbc-testing-support"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-3-jdbc-testing-support"}},[e._v("#")]),e._v(" 3.3. JDBC Testing Support")]),e._v(" "),n("p",[e._v("The "),n("code",[e._v("org.springframework.test.jdbc")]),e._v(" package contains "),n("code",[e._v("JdbcTestUtils")]),e._v(", which is a\ncollection of JDBC-related utility functions intended to simplify standard database\ntesting scenarios. Specifically, "),n("code",[e._v("JdbcTestUtils")]),e._v(" provides the following static utility\nmethods.")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("countRowsInTable(..)")]),e._v(": Counts the number of rows in the given table.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("countRowsInTableWhere(..)")]),e._v(": Counts the number of rows in the given table by using the\nprovided "),n("code",[e._v("WHERE")]),e._v(" clause.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("deleteFromTables(..)")]),e._v(": Deletes all rows from the specified tables.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("deleteFromTableWhere(..)")]),e._v(": Deletes rows from the given table by using the provided"),n("code",[e._v("WHERE")]),e._v(" clause.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("dropTables(..)")]),e._v(": Drops the specified tables.")])])]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[n("a",{attrs:{href:"#testcontext-support-classes-junit4"}},[n("code",[e._v("AbstractTransactionalJUnit4SpringContextTests")])]),e._v("and "),n("a",{attrs:{href:"#testcontext-support-classes-testng"}},[n("code",[e._v("AbstractTransactionalTestNGSpringContextTests")])]),e._v("provide convenience methods that delegate to the aforementioned methods in"),n("code",[e._v("JdbcTestUtils")]),e._v("."),n("br"),n("br"),e._v("The "),n("code",[e._v("spring-jdbc")]),e._v(" module provides support for configuring and launching an embedded"),n("br"),e._v("database, which you can use in integration tests that interact with a database."),n("br"),e._v("For details, see "),n("RouterLink",{attrs:{to:"/en/spring-framework/data-access.html#jdbc-embedded-database-support"}},[e._v("Embedded Database"),n("br"),e._v("Support")]),e._v(" and "),n("RouterLink",{attrs:{to:"/en/spring-framework/data-access.html#jdbc-embedded-database-dao-testing"}},[e._v("Testing Data Access"),n("br"),e._v("Logic with an Embedded Database")]),e._v(".")],1)])]),e._v(" "),n("tbody")]),e._v(" "),n("h3",{attrs:{id:"_3-4-annotations"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-4-annotations"}},[e._v("#")]),e._v(" 3.4. Annotations")]),e._v(" "),n("p",[e._v("This section covers annotations that you can use when you test Spring applications.\nIt includes the following topics:")]),e._v(" "),n("ul",[n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-spring"}},[e._v("Spring Testing Annotations")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-standard"}},[e._v("Standard Annotation Support")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-junit4"}},[e._v("Spring JUnit 4 Testing Annotations")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-junit-jupiter"}},[e._v("Spring JUnit Jupiter Testing Annotations")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-meta"}},[e._v("Meta-Annotation Support for Testing")])])])]),e._v(" "),n("h4",{attrs:{id:"_3-4-1-spring-testing-annotations"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-4-1-spring-testing-annotations"}},[e._v("#")]),e._v(" 3.4.1. Spring Testing Annotations")]),e._v(" "),n("p",[e._v("The Spring Framework provides the following set of Spring-specific annotations that you\ncan use in your unit and integration tests in conjunction with the TestContext framework.\nSee the corresponding javadoc for further information, including default attribute\nvalues, attribute aliases, and other details.")]),e._v(" "),n("p",[e._v("Spring’s testing annotations include the following:")]),e._v(" "),n("ul",[n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-bootstrapwith"}},[n("code",[e._v("@BootstrapWith")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-contextconfiguration"}},[n("code",[e._v("@ContextConfiguration")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-webappconfiguration"}},[n("code",[e._v("@WebAppConfiguration")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-contexthierarchy"}},[n("code",[e._v("@ContextHierarchy")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-activeprofiles"}},[n("code",[e._v("@ActiveProfiles")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-testpropertysource"}},[n("code",[e._v("@TestPropertySource")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-dynamicpropertysource"}},[n("code",[e._v("@DynamicPropertySource")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-dirtiescontext"}},[n("code",[e._v("@DirtiesContext")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-testexecutionlisteners"}},[n("code",[e._v("@TestExecutionListeners")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-recordapplicationevents"}},[n("code",[e._v("@RecordApplicationEvents")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-commit"}},[n("code",[e._v("@Commit")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-rollback"}},[n("code",[e._v("@Rollback")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-beforetransaction"}},[n("code",[e._v("@BeforeTransaction")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-aftertransaction"}},[n("code",[e._v("@AfterTransaction")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-sql"}},[n("code",[e._v("@Sql")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-sqlconfig"}},[n("code",[e._v("@SqlConfig")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-sqlmergemode"}},[n("code",[e._v("@SqlMergeMode")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-sqlgroup"}},[n("code",[e._v("@SqlGroup")])])])])]),e._v(" "),n("h5",{attrs:{id:"bootstrapwith"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#bootstrapwith"}},[e._v("#")]),e._v(" "),n("code",[e._v("@BootstrapWith")])]),e._v(" "),n("p",[n("code",[e._v("@BootstrapWith")]),e._v(" is a class-level annotation that you can use to configure how the Spring\nTestContext Framework is bootstrapped. Specifically, you can use "),n("code",[e._v("@BootstrapWith")]),e._v(" to\nspecify a custom "),n("code",[e._v("TestContextBootstrapper")]),e._v(". See the section on"),n("a",{attrs:{href:"#testcontext-bootstrapping"}},[e._v("bootstrapping the TestContext framework")]),e._v(" for further details.")]),e._v(" "),n("h5",{attrs:{id:"contextconfiguration"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#contextconfiguration"}},[e._v("#")]),e._v(" "),n("code",[e._v("@ContextConfiguration")])]),e._v(" "),n("p",[n("code",[e._v("@ContextConfiguration")]),e._v(" defines class-level metadata that is used to determine how to\nload and configure an "),n("code",[e._v("ApplicationContext")]),e._v(" for integration tests. Specifically,"),n("code",[e._v("@ContextConfiguration")]),e._v(" declares the application context resource "),n("code",[e._v("locations")]),e._v(" or the\ncomponent "),n("code",[e._v("classes")]),e._v(" used to load the context.")]),e._v(" "),n("p",[e._v("Resource locations are typically XML configuration files or Groovy scripts located in the\nclasspath, while component classes are typically "),n("code",[e._v("@Configuration")]),e._v(" classes. However,\nresource locations can also refer to files and scripts in the file system, and component\nclasses can be "),n("code",[e._v("@Component")]),e._v(" classes, "),n("code",[e._v("@Service")]),e._v(" classes, and so on. See"),n("a",{attrs:{href:"#testcontext-ctx-management-javaconfig-component-classes"}},[e._v("Component Classes")]),e._v(" for further details.")]),e._v(" "),n("p",[e._v("The following example shows a "),n("code",[e._v("@ContextConfiguration")]),e._v(" annotation that refers to an XML\nfile:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration("/test-config.xml") (1)\nclass XmlApplicationContextTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Referring to an XML file.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration("/test-config.xml") (1)\nclass XmlApplicationContextTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Referring to an XML file.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("The following example shows a "),n("code",[e._v("@ContextConfiguration")]),e._v(" annotation that refers to a class:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ContextConfiguration(classes = TestConfig.class) (1)\nclass ConfigClassApplicationContextTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Referring to a class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ContextConfiguration(classes = [TestConfig::class]) (1)\nclass ConfigClassApplicationContextTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Referring to a class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("As an alternative or in addition to declaring resource locations or component classes,\nyou can use "),n("code",[e._v("@ContextConfiguration")]),e._v(" to declare "),n("code",[e._v("ApplicationContextInitializer")]),e._v(" classes.\nThe following example shows such a case:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ContextConfiguration(initializers = CustomContextIntializer.class) (1)\nclass ContextInitializerTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Declaring an initializer class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ContextConfiguration(initializers = [CustomContextIntializer::class]) (1)\nclass ContextInitializerTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Declaring an initializer class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("You can optionally use "),n("code",[e._v("@ContextConfiguration")]),e._v(" to declare the "),n("code",[e._v("ContextLoader")]),e._v(" strategy as\nwell. Note, however, that you typically do not need to explicitly configure the loader,\nsince the default loader supports "),n("code",[e._v("initializers")]),e._v(" and either resource "),n("code",[e._v("locations")]),e._v(" or\ncomponent "),n("code",[e._v("classes")]),e._v(".")]),e._v(" "),n("p",[e._v("The following example uses both a location and a loader:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration(locations = "/test-context.xml", loader = CustomContextLoader.class) (1)\nclass CustomLoaderXmlApplicationContextTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Configuring both a location and a custom loader.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration("/test-context.xml", loader = CustomContextLoader::class) (1)\nclass CustomLoaderXmlApplicationContextTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Configuring both a location and a custom loader.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[n("code",[e._v("@ContextConfiguration")]),e._v(" provides support for inheriting resource locations or"),n("br"),e._v("configuration classes as well as context initializers that are declared by superclasses"),n("br"),e._v("or enclosing classes.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("See "),n("a",{attrs:{href:"#testcontext-ctx-management"}},[e._v("Context Management")]),e._v(","),n("a",{attrs:{href:"#testcontext-junit-jupiter-nested-test-configuration"}},[n("code",[e._v("@Nested")]),e._v(" test class configuration")]),e._v(", and the "),n("code",[e._v("@ContextConfiguration")]),e._v("javadocs for further details.")]),e._v(" "),n("h5",{attrs:{id:"webappconfiguration"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#webappconfiguration"}},[e._v("#")]),e._v(" "),n("code",[e._v("@WebAppConfiguration")])]),e._v(" "),n("p",[n("code",[e._v("@WebAppConfiguration")]),e._v(" is a class-level annotation that you can use to declare that the"),n("code",[e._v("ApplicationContext")]),e._v(" loaded for an integration test should be a "),n("code",[e._v("WebApplicationContext")]),e._v(".\nThe mere presence of "),n("code",[e._v("@WebAppConfiguration")]),e._v(" on a test class ensures that a"),n("code",[e._v("WebApplicationContext")]),e._v(" is loaded for the test, using the default value of"),n("code",[e._v('"file:src/main/webapp"')]),e._v(" for the path to the root of the web application (that is, the\nresource base path). The resource base path is used behind the scenes to create a"),n("code",[e._v("MockServletContext")]),e._v(", which serves as the "),n("code",[e._v("ServletContext")]),e._v(" for the test’s"),n("code",[e._v("WebApplicationContext")]),e._v(".")]),e._v(" "),n("p",[e._v("The following example shows how to use the "),n("code",[e._v("@WebAppConfiguration")]),e._v(" annotation:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ContextConfiguration\n@WebAppConfiguration (1)\nclass WebAppTests {\n // class body...\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ContextConfiguration\n@WebAppConfiguration (1)\nclass WebAppTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("The "),n("code",[e._v("@WebAppConfiguration")]),e._v(" annotation.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("To override the default, you can specify a different base resource path by using the\nimplicit "),n("code",[e._v("value")]),e._v(" attribute. Both "),n("code",[e._v("classpath:")]),e._v(" and "),n("code",[e._v("file:")]),e._v(" resource prefixes are\nsupported. If no resource prefix is supplied, the path is assumed to be a file system\nresource. The following example shows how to specify a classpath resource:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@WebAppConfiguration("classpath:test-web-resources") (1)\nclass WebAppTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying a classpath resource.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@WebAppConfiguration("classpath:test-web-resources") (1)\nclass WebAppTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying a classpath resource.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Note that "),n("code",[e._v("@WebAppConfiguration")]),e._v(" must be used in conjunction with"),n("code",[e._v("@ContextConfiguration")]),e._v(", either within a single test class or within a test class\nhierarchy. See the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/web/WebAppConfiguration.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@WebAppConfiguration")]),n("OutboundLink")],1),e._v("javadoc for further details.")]),e._v(" "),n("h5",{attrs:{id:"contexthierarchy"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#contexthierarchy"}},[e._v("#")]),e._v(" "),n("code",[e._v("@ContextHierarchy")])]),e._v(" "),n("p",[n("code",[e._v("@ContextHierarchy")]),e._v(" is a class-level annotation that is used to define a hierarchy of"),n("code",[e._v("ApplicationContext")]),e._v(" instances for integration tests. "),n("code",[e._v("@ContextHierarchy")]),e._v(" should be\ndeclared with a list of one or more "),n("code",[e._v("@ContextConfiguration")]),e._v(" instances, each of which\ndefines a level in the context hierarchy. The following examples demonstrate the use of"),n("code",[e._v("@ContextHierarchy")]),e._v(" within a single test class ("),n("code",[e._v("@ContextHierarchy")]),e._v(" can also be used\nwithin a test class hierarchy):")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextHierarchy({\n @ContextConfiguration("/parent-config.xml"),\n @ContextConfiguration("/child-config.xml")\n})\nclass ContextHierarchyTests {\n // class body...\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextHierarchy(\n ContextConfiguration("/parent-config.xml"),\n ContextConfiguration("/child-config.xml"))\nclass ContextHierarchyTests {\n // class body...\n}\n')])])]),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@WebAppConfiguration\n@ContextHierarchy({\n @ContextConfiguration(classes = AppConfig.class),\n @ContextConfiguration(classes = WebConfig.class)\n})\nclass WebIntegrationTests {\n // class body...\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@WebAppConfiguration\n@ContextHierarchy(\n ContextConfiguration(classes = [AppConfig::class]),\n ContextConfiguration(classes = [WebConfig::class]))\nclass WebIntegrationTests {\n // class body...\n}\n")])])]),n("p",[e._v("If you need to merge or override the configuration for a given level of the context\nhierarchy within a test class hierarchy, you must explicitly name that level by supplying\nthe same value to the "),n("code",[e._v("name")]),e._v(" attribute in "),n("code",[e._v("@ContextConfiguration")]),e._v(" at each corresponding\nlevel in the class hierarchy. See "),n("a",{attrs:{href:"#testcontext-ctx-management-ctx-hierarchies"}},[e._v("Context Hierarchies")]),e._v(" and the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/ContextHierarchy.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@ContextHierarchy")]),n("OutboundLink")],1),e._v(" javadoc\nfor further examples.")]),e._v(" "),n("h5",{attrs:{id:"activeprofiles"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#activeprofiles"}},[e._v("#")]),e._v(" "),n("code",[e._v("@ActiveProfiles")])]),e._v(" "),n("p",[n("code",[e._v("@ActiveProfiles")]),e._v(" is a class-level annotation that is used to declare which bean\ndefinition profiles should be active when loading an "),n("code",[e._v("ApplicationContext")]),e._v(" for an\nintegration test.")]),e._v(" "),n("p",[e._v("The following example indicates that the "),n("code",[e._v("dev")]),e._v(" profile should be active:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@ActiveProfiles("dev") (1)\nclass DeveloperTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Indicate that the "),n("code",[e._v("dev")]),e._v(" profile should be active.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@ActiveProfiles("dev") (1)\nclass DeveloperTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Indicate that the "),n("code",[e._v("dev")]),e._v(" profile should be active.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("The following example indicates that both the "),n("code",[e._v("dev")]),e._v(" and the "),n("code",[e._v("integration")]),e._v(" profiles should\nbe active:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@ActiveProfiles({"dev", "integration"}) (1)\nclass DeveloperIntegrationTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Indicate that the "),n("code",[e._v("dev")]),e._v(" and "),n("code",[e._v("integration")]),e._v(" profiles should be active.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@ActiveProfiles(["dev", "integration"]) (1)\nclass DeveloperIntegrationTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Indicate that the "),n("code",[e._v("dev")]),e._v(" and "),n("code",[e._v("integration")]),e._v(" profiles should be active.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[n("code",[e._v("@ActiveProfiles")]),e._v(" provides support for inheriting active bean definition profiles"),n("br"),e._v("declared by superclasses and enclosing classes by default. You can also resolve active"),n("br"),e._v("bean definition profiles programmatically by implementing a custom"),n("a",{attrs:{href:"#testcontext-ctx-management-env-profiles-ActiveProfilesResolver"}},[n("code",[e._v("ActiveProfilesResolver")])]),e._v("and registering it by using the "),n("code",[e._v("resolver")]),e._v(" attribute of "),n("code",[e._v("@ActiveProfiles")]),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("See "),n("a",{attrs:{href:"#testcontext-ctx-management-env-profiles"}},[e._v("Context Configuration with Environment Profiles")]),e._v(","),n("a",{attrs:{href:"#testcontext-junit-jupiter-nested-test-configuration"}},[n("code",[e._v("@Nested")]),e._v(" test class configuration")]),e._v(", and the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/ActiveProfiles.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@ActiveProfiles")]),n("OutboundLink")],1),e._v(" javadoc for\nexamples and further details.")]),e._v(" "),n("h5",{attrs:{id:"testpropertysource"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#testpropertysource"}},[e._v("#")]),e._v(" "),n("code",[e._v("@TestPropertySource")])]),e._v(" "),n("p",[n("code",[e._v("@TestPropertySource")]),e._v(" is a class-level annotation that you can use to configure the\nlocations of properties files and inlined properties to be added to the set of"),n("code",[e._v("PropertySources")]),e._v(" in the "),n("code",[e._v("Environment")]),e._v(" for an "),n("code",[e._v("ApplicationContext")]),e._v(" loaded for an\nintegration test.")]),e._v(" "),n("p",[e._v("The following example demonstrates how to declare a properties file from the classpath:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@TestPropertySource("/test.properties") (1)\nclass MyIntegrationTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Get properties from "),n("code",[e._v("test.properties")]),e._v(" in the root of the classpath.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@TestPropertySource("/test.properties") (1)\nclass MyIntegrationTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Get properties from "),n("code",[e._v("test.properties")]),e._v(" in the root of the classpath.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("The following example demonstrates how to declare inlined properties:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@TestPropertySource(properties = { "timezone = GMT", "port: 4242" }) (1)\nclass MyIntegrationTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Declare "),n("code",[e._v("timezone")]),e._v(" and "),n("code",[e._v("port")]),e._v(" properties.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@TestPropertySource(properties = ["timezone = GMT", "port: 4242"]) (1)\nclass MyIntegrationTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Declare "),n("code",[e._v("timezone")]),e._v(" and "),n("code",[e._v("port")]),e._v(" properties.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("See "),n("a",{attrs:{href:"#testcontext-ctx-management-property-sources"}},[e._v("Context Configuration with Test Property Sources")]),e._v(" for examples and further details.")]),e._v(" "),n("h5",{attrs:{id:"dynamicpropertysource"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#dynamicpropertysource"}},[e._v("#")]),e._v(" "),n("code",[e._v("@DynamicPropertySource")])]),e._v(" "),n("p",[n("code",[e._v("@DynamicPropertySource")]),e._v(" is a method-level annotation that you can use to register"),n("em",[e._v("dynamic")]),e._v(" properties to be added to the set of "),n("code",[e._v("PropertySources")]),e._v(" in the "),n("code",[e._v("Environment")]),e._v(" for\nan "),n("code",[e._v("ApplicationContext")]),e._v(" loaded for an integration test. Dynamic properties are useful\nwhen you do not know the value of the properties upfront – for example, if the properties\nare managed by an external resource such as for a container managed by the"),n("a",{attrs:{href:"https://www.testcontainers.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Testcontainers"),n("OutboundLink")],1),e._v(" project.")]),e._v(" "),n("p",[e._v("The following example demonstrates how to register a dynamic property:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\nclass MyIntegrationTests {\n\n static MyExternalServer server = // ...\n\n @DynamicPropertySource (1)\n static void dynamicProperties(DynamicPropertyRegistry registry) { (2)\n registry.add("server.port", server::getPort); (3)\n }\n\n // tests ...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Annotate a "),n("code",[e._v("static")]),e._v(" method with "),n("code",[e._v("@DynamicPropertySource")]),e._v(".")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Accept a "),n("code",[e._v("DynamicPropertyRegistry")]),e._v(" as an argument.")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("3")])]),e._v(" "),n("td",[e._v("Register a dynamic "),n("code",[e._v("server.port")]),e._v(" property to be retrieved lazily from the server.")])])])]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\nclass MyIntegrationTests {\n\n companion object {\n\n @JvmStatic\n val server: MyExternalServer = // ...\n\n @DynamicPropertySource (1)\n @JvmStatic\n fun dynamicProperties(registry: DynamicPropertyRegistry) { (2)\n registry.add("server.port", server::getPort) (3)\n }\n }\n\n // tests ...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Annotate a "),n("code",[e._v("static")]),e._v(" method with "),n("code",[e._v("@DynamicPropertySource")]),e._v(".")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Accept a "),n("code",[e._v("DynamicPropertyRegistry")]),e._v(" as an argument.")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("3")])]),e._v(" "),n("td",[e._v("Register a dynamic "),n("code",[e._v("server.port")]),e._v(" property to be retrieved lazily from the server.")])])])]),e._v(" "),n("p",[e._v("See "),n("a",{attrs:{href:"#testcontext-ctx-management-dynamic-property-sources"}},[e._v("Context Configuration with Dynamic Property Sources")]),e._v(" for further details.")]),e._v(" "),n("h5",{attrs:{id:"dirtiescontext"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#dirtiescontext"}},[e._v("#")]),e._v(" "),n("code",[e._v("@DirtiesContext")])]),e._v(" "),n("p",[n("code",[e._v("@DirtiesContext")]),e._v(" indicates that the underlying Spring "),n("code",[e._v("ApplicationContext")]),e._v(" has been\ndirtied during the execution of a test (that is, the test modified or corrupted it in\nsome manner — for example, by changing the state of a singleton bean) and should be\nclosed. When an application context is marked as dirty, it is removed from the testing\nframework’s cache and closed. As a consequence, the underlying Spring container is\nrebuilt for any subsequent test that requires a context with the same configuration\nmetadata.")]),e._v(" "),n("p",[e._v("You can use "),n("code",[e._v("@DirtiesContext")]),e._v(" as both a class-level and a method-level annotation within\nthe same class or class hierarchy. In such scenarios, the "),n("code",[e._v("ApplicationContext")]),e._v(" is marked\nas dirty before or after any such annotated method as well as before or after the current\ntest class, depending on the configured "),n("code",[e._v("methodMode")]),e._v(" and "),n("code",[e._v("classMode")]),e._v(".")]),e._v(" "),n("p",[e._v("The following examples explain when the context would be dirtied for various\nconfiguration scenarios:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("Before the current test class, when declared on a class with class mode set to"),n("code",[e._v("BEFORE_CLASS")]),e._v(".")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@DirtiesContext(classMode = BEFORE_CLASS) (1)\nclass FreshContextTests {\n // some tests that require a new Spring container\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Dirty the context before the current test class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@DirtiesContext(classMode = BEFORE_CLASS) (1)\nclass FreshContextTests {\n // some tests that require a new Spring container\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Dirty the context before the current test class.")])])]),e._v(" "),n("tbody")])]),e._v(" "),n("li",[n("p",[e._v("After the current test class, when declared on a class with class mode set to"),n("code",[e._v("AFTER_CLASS")]),e._v(" (i.e., the default class mode).")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@DirtiesContext (1)\nclass ContextDirtyingTests {\n // some tests that result in the Spring container being dirtied\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Dirty the context after the current test class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@DirtiesContext (1)\nclass ContextDirtyingTests {\n // some tests that result in the Spring container being dirtied\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Dirty the context after the current test class.")])])]),e._v(" "),n("tbody")])]),e._v(" "),n("li",[n("p",[e._v("Before each test method in the current test class, when declared on a class with class\nmode set to "),n("code",[e._v("BEFORE_EACH_TEST_METHOD.")])]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@DirtiesContext(classMode = BEFORE_EACH_TEST_METHOD) (1)\nclass FreshContextTests {\n // some tests that require a new Spring container\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Dirty the context before each test method.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@DirtiesContext(classMode = BEFORE_EACH_TEST_METHOD) (1)\nclass FreshContextTests {\n // some tests that require a new Spring container\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Dirty the context before each test method.")])])]),e._v(" "),n("tbody")])]),e._v(" "),n("li",[n("p",[e._v("After each test method in the current test class, when declared on a class with class\nmode set to "),n("code",[e._v("AFTER_EACH_TEST_METHOD.")])]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) (1)\nclass ContextDirtyingTests {\n // some tests that result in the Spring container being dirtied\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Dirty the context after each test method.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) (1)\nclass ContextDirtyingTests {\n // some tests that result in the Spring container being dirtied\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Dirty the context after each test method.")])])]),e._v(" "),n("tbody")])]),e._v(" "),n("li",[n("p",[e._v("Before the current test, when declared on a method with the method mode set to"),n("code",[e._v("BEFORE_METHOD")]),e._v(".")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@DirtiesContext(methodMode = BEFORE_METHOD) (1)\n@Test\nvoid testProcessWhichRequiresFreshAppCtx() {\n // some logic that requires a new Spring container\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Dirty the context before the current test method.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@DirtiesContext(methodMode = BEFORE_METHOD) (1)\n@Test\nfun testProcessWhichRequiresFreshAppCtx() {\n // some logic that requires a new Spring container\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Dirty the context before the current test method.")])])]),e._v(" "),n("tbody")])]),e._v(" "),n("li",[n("p",[e._v("After the current test, when declared on a method with the method mode set to"),n("code",[e._v("AFTER_METHOD")]),e._v(" (i.e., the default method mode).")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@DirtiesContext (1)\n@Test\nvoid testProcessWhichDirtiesAppCtx() {\n // some logic that results in the Spring container being dirtied\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Dirty the context after the current test method.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@DirtiesContext (1)\n@Test\nfun testProcessWhichDirtiesAppCtx() {\n // some logic that results in the Spring container being dirtied\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Dirty the context after the current test method.")])])]),e._v(" "),n("tbody")])])]),e._v(" "),n("p",[e._v("If you use "),n("code",[e._v("@DirtiesContext")]),e._v(" in a test whose context is configured as part of a context\nhierarchy with "),n("code",[e._v("@ContextHierarchy")]),e._v(", you can use the "),n("code",[e._v("hierarchyMode")]),e._v(" flag to control how\nthe context cache is cleared. By default, an exhaustive algorithm is used to clear the\ncontext cache, including not only the current level but also all other context\nhierarchies that share an ancestor context common to the current test. All"),n("code",[e._v("ApplicationContext")]),e._v(" instances that reside in a sub-hierarchy of the common ancestor\ncontext are removed from the context cache and closed. If the exhaustive algorithm is\noverkill for a particular use case, you can specify the simpler current level algorithm,\nas the following example shows.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextHierarchy({\n @ContextConfiguration("/parent-config.xml"),\n @ContextConfiguration("/child-config.xml")\n})\nclass BaseTests {\n // class body...\n}\n\nclass ExtendedTests extends BaseTests {\n\n @Test\n @DirtiesContext(hierarchyMode = CURRENT_LEVEL) (1)\n void test() {\n // some logic that results in the child context being dirtied\n }\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Use the current-level algorithm.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextHierarchy(\n ContextConfiguration("/parent-config.xml"),\n ContextConfiguration("/child-config.xml"))\nopen class BaseTests {\n // class body...\n}\n\nclass ExtendedTests : BaseTests() {\n\n @Test\n @DirtiesContext(hierarchyMode = CURRENT_LEVEL) (1)\n fun test() {\n // some logic that results in the child context being dirtied\n }\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Use the current-level algorithm.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("For further details regarding the "),n("code",[e._v("EXHAUSTIVE")]),e._v(" and "),n("code",[e._v("CURRENT_LEVEL")]),e._v(" algorithms, see the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/annotation/DirtiesContext.HierarchyMode.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("DirtiesContext.HierarchyMode")]),n("OutboundLink")],1),e._v("javadoc.")]),e._v(" "),n("h5",{attrs:{id:"testexecutionlisteners"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#testexecutionlisteners"}},[e._v("#")]),e._v(" "),n("code",[e._v("@TestExecutionListeners")])]),e._v(" "),n("p",[n("code",[e._v("@TestExecutionListeners")]),e._v(" defines class-level metadata for configuring the"),n("code",[e._v("TestExecutionListener")]),e._v(" implementations that should be registered with the"),n("code",[e._v("TestContextManager")]),e._v(". Typically, "),n("code",[e._v("@TestExecutionListeners")]),e._v(" is used in conjunction with"),n("code",[e._v("@ContextConfiguration")]),e._v(".")]),e._v(" "),n("p",[e._v("The following example shows how to register two "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ContextConfiguration\n@TestExecutionListeners({CustomTestExecutionListener.class, AnotherTestExecutionListener.class}) (1)\nclass CustomTestExecutionListenerTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Register two "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ContextConfiguration\n@TestExecutionListeners(CustomTestExecutionListener::class, AnotherTestExecutionListener::class) (1)\nclass CustomTestExecutionListenerTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Register two "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("By default, "),n("code",[e._v("@TestExecutionListeners")]),e._v(" provides support for inheriting listeners from\nsuperclasses or enclosing classes. See"),n("a",{attrs:{href:"#testcontext-junit-jupiter-nested-test-configuration"}},[n("code",[e._v("@Nested")]),e._v(" test class configuration")]),e._v(" and the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/TestExecutionListeners.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@TestExecutionListeners")]),e._v("javadoc"),n("OutboundLink")],1),e._v(" for an example and further details.")]),e._v(" "),n("h5",{attrs:{id:"recordapplicationevents"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#recordapplicationevents"}},[e._v("#")]),e._v(" "),n("code",[e._v("@RecordApplicationEvents")])]),e._v(" "),n("p",[n("code",[e._v("@RecordApplicationEvents")]),e._v(" is a class-level annotation that is used to instruct the"),n("em",[e._v("Spring TestContext Framework")]),e._v(" to record all application events that are published in the"),n("code",[e._v("ApplicationContext")]),e._v(" during the execution of a single test.")]),e._v(" "),n("p",[e._v("The recorded events can be accessed via the "),n("code",[e._v("ApplicationEvents")]),e._v(" API within tests.")]),e._v(" "),n("p",[e._v("See "),n("a",{attrs:{href:"#testcontext-application-events"}},[e._v("Application Events")]),e._v(" and the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/event/RecordApplicationEvents.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@RecordApplicationEvents")]),e._v("javadoc"),n("OutboundLink")],1),e._v(" for an example and further details.")]),e._v(" "),n("h5",{attrs:{id:"commit"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#commit"}},[e._v("#")]),e._v(" "),n("code",[e._v("@Commit")])]),e._v(" "),n("p",[n("code",[e._v("@Commit")]),e._v(" indicates that the transaction for a transactional test method should be\ncommitted after the test method has completed. You can use "),n("code",[e._v("@Commit")]),e._v(" as a direct\nreplacement for "),n("code",[e._v("@Rollback(false)")]),e._v(" to more explicitly convey the intent of the code.\nAnalogous to "),n("code",[e._v("@Rollback")]),e._v(", "),n("code",[e._v("@Commit")]),e._v(" can also be declared as a class-level or method-level\nannotation.")]),e._v(" "),n("p",[e._v("The following example shows how to use the "),n("code",[e._v("@Commit")]),e._v(" annotation:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Commit (1)\n@Test\nvoid testProcessWithoutRollback() {\n // ...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Commit the result of the test to the database.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Commit (1)\n@Test\nfun testProcessWithoutRollback() {\n // ...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Commit the result of the test to the database.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"rollback"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#rollback"}},[e._v("#")]),e._v(" "),n("code",[e._v("@Rollback")])]),e._v(" "),n("p",[n("code",[e._v("@Rollback")]),e._v(" indicates whether the transaction for a transactional test method should be\nrolled back after the test method has completed. If "),n("code",[e._v("true")]),e._v(", the transaction is rolled\nback. Otherwise, the transaction is committed (see also"),n("a",{attrs:{href:"#spring-testing-annotation-commit"}},[n("code",[e._v("@Commit")])]),e._v("). Rollback for integration tests in the Spring\nTestContext Framework defaults to "),n("code",[e._v("true")]),e._v(" even if "),n("code",[e._v("@Rollback")]),e._v(" is not explicitly declared.")]),e._v(" "),n("p",[e._v("When declared as a class-level annotation, "),n("code",[e._v("@Rollback")]),e._v(" defines the default rollback\nsemantics for all test methods within the test class hierarchy. When declared as a\nmethod-level annotation, "),n("code",[e._v("@Rollback")]),e._v(" defines rollback semantics for the specific test\nmethod, potentially overriding class-level "),n("code",[e._v("@Rollback")]),e._v(" or "),n("code",[e._v("@Commit")]),e._v(" semantics.")]),e._v(" "),n("p",[e._v("The following example causes a test method’s result to not be rolled back (that is, the\nresult is committed to the database):")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Rollback(false) (1)\n@Test\nvoid testProcessWithoutRollback() {\n // ...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Do not roll back the result.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Rollback(false) (1)\n@Test\nfun testProcessWithoutRollback() {\n // ...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Do not roll back the result.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"beforetransaction"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#beforetransaction"}},[e._v("#")]),e._v(" "),n("code",[e._v("@BeforeTransaction")])]),e._v(" "),n("p",[n("code",[e._v("@BeforeTransaction")]),e._v(" indicates that the annotated "),n("code",[e._v("void")]),e._v(" method should be run before a\ntransaction is started, for test methods that have been configured to run within a\ntransaction by using Spring’s "),n("code",[e._v("@Transactional")]),e._v(" annotation. "),n("code",[e._v("@BeforeTransaction")]),e._v(" methods\nare not required to be "),n("code",[e._v("public")]),e._v(" and may be declared on Java 8-based interface default\nmethods.")]),e._v(" "),n("p",[e._v("The following example shows how to use the "),n("code",[e._v("@BeforeTransaction")]),e._v(" annotation:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@BeforeTransaction (1)\nvoid beforeTransaction() {\n // logic to be run before a transaction is started\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Run this method before a transaction.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@BeforeTransaction (1)\nfun beforeTransaction() {\n // logic to be run before a transaction is started\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Run this method before a transaction.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"aftertransaction"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#aftertransaction"}},[e._v("#")]),e._v(" "),n("code",[e._v("@AfterTransaction")])]),e._v(" "),n("p",[n("code",[e._v("@AfterTransaction")]),e._v(" indicates that the annotated "),n("code",[e._v("void")]),e._v(" method should be run after a\ntransaction is ended, for test methods that have been configured to run within a\ntransaction by using Spring’s "),n("code",[e._v("@Transactional")]),e._v(" annotation. "),n("code",[e._v("@AfterTransaction")]),e._v(" methods\nare not required to be "),n("code",[e._v("public")]),e._v(" and may be declared on Java 8-based interface default\nmethods.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@AfterTransaction (1)\nvoid afterTransaction() {\n // logic to be run after a transaction has ended\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Run this method after a transaction.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@AfterTransaction (1)\nfun afterTransaction() {\n // logic to be run after a transaction has ended\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Run this method after a transaction.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"sql"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#sql"}},[e._v("#")]),e._v(" "),n("code",[e._v("@Sql")])]),e._v(" "),n("p",[n("code",[e._v("@Sql")]),e._v(" is used to annotate a test class or test method to configure SQL scripts to be run\nagainst a given database during integration tests. The following example shows how to use\nit:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\n@Sql({"/test-schema.sql", "/test-user-data.sql"}) (1)\nvoid userTest() {\n // run code that relies on the test schema and test data\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Run two scripts for this test.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\n@Sql("/test-schema.sql", "/test-user-data.sql") (1)\nfun userTest() {\n // run code that relies on the test schema and test data\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Run two scripts for this test.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("See "),n("a",{attrs:{href:"#testcontext-executing-sql-declaratively"}},[e._v("Executing SQL scripts declaratively with @Sql")]),e._v(" for further details.")]),e._v(" "),n("h5",{attrs:{id:"sqlconfig"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#sqlconfig"}},[e._v("#")]),e._v(" "),n("code",[e._v("@SqlConfig")])]),e._v(" "),n("p",[n("code",[e._v("@SqlConfig")]),e._v(" defines metadata that is used to determine how to parse and run SQL scripts\nconfigured with the "),n("code",[e._v("@Sql")]),e._v(" annotation. The following example shows how to use it:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\n@Sql(\n scripts = "/test-user-data.sql",\n config = @SqlConfig(commentPrefix = "`", separator = "@@") (1)\n)\nvoid userTest() {\n // run code that relies on the test data\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Set the comment prefix and the separator in SQL scripts.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\n@Sql("/test-user-data.sql", config = SqlConfig(commentPrefix = "`", separator = "@@")) (1)\nfun userTest() {\n // run code that relies on the test data\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Set the comment prefix and the separator in SQL scripts.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"sqlmergemode"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#sqlmergemode"}},[e._v("#")]),e._v(" "),n("code",[e._v("@SqlMergeMode")])]),e._v(" "),n("p",[n("code",[e._v("@SqlMergeMode")]),e._v(" is used to annotate a test class or test method to configure whether\nmethod-level "),n("code",[e._v("@Sql")]),e._v(" declarations are merged with class-level "),n("code",[e._v("@Sql")]),e._v(" declarations. If"),n("code",[e._v("@SqlMergeMode")]),e._v(" is not declared on a test class or test method, the "),n("code",[e._v("OVERRIDE")]),e._v(" merge mode\nwill be used by default. With the "),n("code",[e._v("OVERRIDE")]),e._v(" mode, method-level "),n("code",[e._v("@Sql")]),e._v(" declarations will\neffectively override class-level "),n("code",[e._v("@Sql")]),e._v(" declarations.")]),e._v(" "),n("p",[e._v("Note that a method-level "),n("code",[e._v("@SqlMergeMode")]),e._v(" declaration overrides a class-level declaration.")]),e._v(" "),n("p",[e._v("The following example shows how to use "),n("code",[e._v("@SqlMergeMode")]),e._v(" at the class level.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(TestConfig.class)\n@Sql("/test-schema.sql")\n@SqlMergeMode(MERGE) (1)\nclass UserTests {\n\n @Test\n @Sql("/user-test-data-001.sql")\n void standardUserProfile() {\n // run code that relies on test data set 001\n }\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Set the "),n("code",[e._v("@Sql")]),e._v(" merge mode to "),n("code",[e._v("MERGE")]),e._v(" for all test methods in the class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(TestConfig::class)\n@Sql("/test-schema.sql")\n@SqlMergeMode(MERGE) (1)\nclass UserTests {\n\n @Test\n @Sql("/user-test-data-001.sql")\n fun standardUserProfile() {\n // run code that relies on test data set 001\n }\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Set the "),n("code",[e._v("@Sql")]),e._v(" merge mode to "),n("code",[e._v("MERGE")]),e._v(" for all test methods in the class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("The following example shows how to use "),n("code",[e._v("@SqlMergeMode")]),e._v(" at the method level.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(TestConfig.class)\n@Sql("/test-schema.sql")\nclass UserTests {\n\n @Test\n @Sql("/user-test-data-001.sql")\n @SqlMergeMode(MERGE) (1)\n void standardUserProfile() {\n // run code that relies on test data set 001\n }\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Set the "),n("code",[e._v("@Sql")]),e._v(" merge mode to "),n("code",[e._v("MERGE")]),e._v(" for a specific test method.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(TestConfig::class)\n@Sql("/test-schema.sql")\nclass UserTests {\n\n @Test\n @Sql("/user-test-data-001.sql")\n @SqlMergeMode(MERGE) (1)\n fun standardUserProfile() {\n // run code that relies on test data set 001\n }\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Set the "),n("code",[e._v("@Sql")]),e._v(" merge mode to "),n("code",[e._v("MERGE")]),e._v(" for a specific test method.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"sqlgroup"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#sqlgroup"}},[e._v("#")]),e._v(" "),n("code",[e._v("@SqlGroup")])]),e._v(" "),n("p",[n("code",[e._v("@SqlGroup")]),e._v(" is a container annotation that aggregates several "),n("code",[e._v("@Sql")]),e._v(" annotations. You can\nuse "),n("code",[e._v("@SqlGroup")]),e._v(" natively to declare several nested "),n("code",[e._v("@Sql")]),e._v(" annotations, or you can use it\nin conjunction with Java 8’s support for repeatable annotations, where "),n("code",[e._v("@Sql")]),e._v(" can be\ndeclared several times on the same class or method, implicitly generating this container\nannotation. The following example shows how to declare an SQL group:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\n@SqlGroup({ (1)\n @Sql(scripts = "/test-schema.sql", config = @SqlConfig(commentPrefix = "`")),\n @Sql("/test-user-data.sql")\n)}\nvoid userTest() {\n // run code that uses the test schema and test data\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Declare a group of SQL scripts.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\n@SqlGroup( (1)\n Sql("/test-schema.sql", config = SqlConfig(commentPrefix = "`")),\n Sql("/test-user-data.sql"))\nfun userTest() {\n // run code that uses the test schema and test data\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Declare a group of SQL scripts.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h4",{attrs:{id:"_3-4-2-standard-annotation-support"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-4-2-standard-annotation-support"}},[e._v("#")]),e._v(" 3.4.2. Standard Annotation Support")]),e._v(" "),n("p",[e._v("The following annotations are supported with standard semantics for all configurations of\nthe Spring TestContext Framework. Note that these annotations are not specific to tests\nand can be used anywhere in the Spring Framework.")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("@Autowired")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Qualifier")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Value")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Resource")]),e._v(" (javax.annotation) if JSR-250 is present")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@ManagedBean")]),e._v(" (javax.annotation) if JSR-250 is present")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Inject")]),e._v(" (javax.inject) if JSR-330 is present")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Named")]),e._v(" (javax.inject) if JSR-330 is present")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@PersistenceContext")]),e._v(" (javax.persistence) if JPA is present")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@PersistenceUnit")]),e._v(" (javax.persistence) if JPA is present")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Required")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Transactional")]),e._v(" (org.springframework.transaction.annotation)"),n("em",[e._v("with "),n("a",{attrs:{href:"#testcontext-tx-attribute-support"}},[e._v("limited attribute support")])])])])]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("JSR-250 Lifecycle Annotations"),n("br"),n("br"),e._v("In the Spring TestContext Framework, you can use "),n("code",[e._v("@PostConstruct")]),e._v(" and "),n("code",[e._v("@PreDestroy")]),e._v(" with"),n("br"),e._v("standard semantics on any application components configured in the "),n("code",[e._v("ApplicationContext")]),e._v("."),n("br"),e._v("However, these lifecycle annotations have limited usage within an actual test class."),n("br"),n("br"),e._v("If a method within a test class is annotated with "),n("code",[e._v("@PostConstruct")]),e._v(", that method runs"),n("br"),e._v("before any before methods of the underlying test framework (for example, methods"),n("br"),e._v("annotated with JUnit Jupiter’s "),n("code",[e._v("@BeforeEach")]),e._v("), and that applies for every test method in"),n("br"),e._v("the test class. On the other hand, if a method within a test class is annotated with"),n("code",[e._v("@PreDestroy")]),e._v(", that method never runs. Therefore, within a test class, we recommend that"),n("br"),e._v("you use test lifecycle callbacks from the underlying test framework instead of"),n("code",[e._v("@PostConstruct")]),e._v(" and "),n("code",[e._v("@PreDestroy")]),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h4",{attrs:{id:"_3-4-3-spring-junit-4-testing-annotations"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-4-3-spring-junit-4-testing-annotations"}},[e._v("#")]),e._v(" 3.4.3. Spring JUnit 4 Testing Annotations")]),e._v(" "),n("p",[e._v("The following annotations are supported only when used in conjunction with the"),n("a",{attrs:{href:"#testcontext-junit4-runner"}},[e._v("SpringRunner")]),e._v(", "),n("a",{attrs:{href:"#testcontext-junit4-rules"}},[e._v("Spring’s JUnit 4\nrules")]),e._v(", or "),n("a",{attrs:{href:"#testcontext-support-classes-junit4"}},[e._v("Spring’s JUnit 4 support classes")]),e._v(":")]),e._v(" "),n("ul",[n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-junit4-ifprofilevalue"}},[n("code",[e._v("@IfProfileValue")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-junit4-profilevaluesourceconfiguration"}},[n("code",[e._v("@ProfileValueSourceConfiguration")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-junit4-timed"}},[n("code",[e._v("@Timed")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-junit4-repeat"}},[n("code",[e._v("@Repeat")])])])])]),e._v(" "),n("h5",{attrs:{id:"ifprofilevalue"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#ifprofilevalue"}},[e._v("#")]),e._v(" "),n("code",[e._v("@IfProfileValue")])]),e._v(" "),n("p",[n("code",[e._v("@IfProfileValue")]),e._v(" indicates that the annotated test is enabled for a specific testing\nenvironment. If the configured "),n("code",[e._v("ProfileValueSource")]),e._v(" returns a matching "),n("code",[e._v("value")]),e._v(" for the\nprovided "),n("code",[e._v("name")]),e._v(", the test is enabled. Otherwise, the test is disabled and, effectively,\nignored.")]),e._v(" "),n("p",[e._v("You can apply "),n("code",[e._v("@IfProfileValue")]),e._v(" at the class level, the method level, or both.\nClass-level usage of "),n("code",[e._v("@IfProfileValue")]),e._v(" takes precedence over method-level usage for any\nmethods within that class or its subclasses. Specifically, a test is enabled if it is\nenabled both at the class level and at the method level. The absence of "),n("code",[e._v("@IfProfileValue")]),e._v("means the test is implicitly enabled. This is analogous to the semantics of JUnit 4’s"),n("code",[e._v("@Ignore")]),e._v(" annotation, except that the presence of "),n("code",[e._v("@Ignore")]),e._v(" always disables a test.")]),e._v(" "),n("p",[e._v("The following example shows a test that has an "),n("code",[e._v("@IfProfileValue")]),e._v(" annotation:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@IfProfileValue(name="java.vendor", value="Oracle Corporation") (1)\n@Test\npublic void testProcessWhichRunsOnlyOnOracleJvm() {\n // some logic that should run only on Java VMs from Oracle Corporation\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v('Run this test only when the Java vendor is "Oracle Corporation".')])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@IfProfileValue(name="java.vendor", value="Oracle Corporation") (1)\n@Test\nfun testProcessWhichRunsOnlyOnOracleJvm() {\n // some logic that should run only on Java VMs from Oracle Corporation\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v('Run this test only when the Java vendor is "Oracle Corporation".')])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Alternatively, you can configure "),n("code",[e._v("@IfProfileValue")]),e._v(" with a list of "),n("code",[e._v("values")]),e._v(" (with "),n("code",[e._v("OR")]),e._v("semantics) to achieve TestNG-like support for test groups in a JUnit 4 environment.\nConsider the following example:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@IfProfileValue(name="test-groups", values={"unit-tests", "integration-tests"}) (1)\n@Test\npublic void testProcessWhichRunsForUnitOrIntegrationTestGroups() {\n // some logic that should run only for unit and integration test groups\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Run this test for unit tests and integration tests.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@IfProfileValue(name="test-groups", values=["unit-tests", "integration-tests"]) (1)\n@Test\nfun testProcessWhichRunsForUnitOrIntegrationTestGroups() {\n // some logic that should run only for unit and integration test groups\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Run this test for unit tests and integration tests.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"profilevaluesourceconfiguration"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#profilevaluesourceconfiguration"}},[e._v("#")]),e._v(" "),n("code",[e._v("@ProfileValueSourceConfiguration")])]),e._v(" "),n("p",[n("code",[e._v("@ProfileValueSourceConfiguration")]),e._v(" is a class-level annotation that specifies what type\nof "),n("code",[e._v("ProfileValueSource")]),e._v(" to use when retrieving profile values configured through the"),n("code",[e._v("@IfProfileValue")]),e._v(" annotation. If "),n("code",[e._v("@ProfileValueSourceConfiguration")]),e._v(" is not declared for a\ntest, "),n("code",[e._v("SystemProfileValueSource")]),e._v(" is used by default. The following example shows how to\nuse "),n("code",[e._v("@ProfileValueSourceConfiguration")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ProfileValueSourceConfiguration(CustomProfileValueSource.class) (1)\npublic class CustomProfileValueSourceTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Use a custom profile value source.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ProfileValueSourceConfiguration(CustomProfileValueSource::class) (1)\nclass CustomProfileValueSourceTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Use a custom profile value source.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"timed"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#timed"}},[e._v("#")]),e._v(" "),n("code",[e._v("@Timed")])]),e._v(" "),n("p",[n("code",[e._v("@Timed")]),e._v(" indicates that the annotated test method must finish execution in a specified\ntime period (in milliseconds). If the text execution time exceeds the specified time\nperiod, the test fails.")]),e._v(" "),n("p",[e._v("The time period includes running the test method itself, any repetitions of the test (see"),n("code",[e._v("@Repeat")]),e._v("), as well as any setting up or tearing down of the test fixture. The following\nexample shows how to use it:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Timed(millis = 1000) (1)\npublic void testProcessWithOneSecondTimeout() {\n // some logic that should not take longer than 1 second to run\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Set the time period for the test to one second.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Timed(millis = 1000) (1)\nfun testProcessWithOneSecondTimeout() {\n // some logic that should not take longer than 1 second to run\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Set the time period for the test to one second.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Spring’s "),n("code",[e._v("@Timed")]),e._v(" annotation has different semantics than JUnit 4’s "),n("code",[e._v("@Test(timeout=…​)")]),e._v("support. Specifically, due to the manner in which JUnit 4 handles test execution timeouts\n(that is, by executing the test method in a separate "),n("code",[e._v("Thread")]),e._v("), "),n("code",[e._v("@Test(timeout=…​)")]),e._v("preemptively fails the test if the test takes too long. Spring’s "),n("code",[e._v("@Timed")]),e._v(", on the other\nhand, does not preemptively fail the test but rather waits for the test to complete\nbefore failing.")]),e._v(" "),n("h5",{attrs:{id:"repeat"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#repeat"}},[e._v("#")]),e._v(" "),n("code",[e._v("@Repeat")])]),e._v(" "),n("p",[n("code",[e._v("@Repeat")]),e._v(" indicates that the annotated test method must be run repeatedly. The number of\ntimes that the test method is to be run is specified in the annotation.")]),e._v(" "),n("p",[e._v("The scope of execution to be repeated includes execution of the test method itself as\nwell as any setting up or tearing down of the test fixture. When used with the"),n("a",{attrs:{href:"#testcontext-junit4-rules"}},[n("code",[e._v("SpringMethodRule")])]),e._v(", the scope additionally includes\npreparation of the test instance by "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations. The\nfollowing example shows how to use the "),n("code",[e._v("@Repeat")]),e._v(" annotation:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Repeat(10) (1)\n@Test\npublic void testProcessRepeatedly() {\n // ...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Repeat this test ten times.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Repeat(10) (1)\n@Test\nfun testProcessRepeatedly() {\n // ...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Repeat this test ten times.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h4",{attrs:{id:"_3-4-4-spring-junit-jupiter-testing-annotations"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-4-4-spring-junit-jupiter-testing-annotations"}},[e._v("#")]),e._v(" 3.4.4. Spring JUnit Jupiter Testing Annotations")]),e._v(" "),n("p",[e._v("The following annotations are supported when used in conjunction with the"),n("a",{attrs:{href:"#testcontext-junit-jupiter-extension"}},[n("code",[e._v("SpringExtension")])]),e._v(" and JUnit Jupiter\n(that is, the programming model in JUnit 5):")]),e._v(" "),n("ul",[n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-junit-jupiter-springjunitconfig"}},[n("code",[e._v("@SpringJUnitConfig")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-junit-jupiter-springjunitwebconfig"}},[n("code",[e._v("@SpringJUnitWebConfig")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-testconstructor"}},[n("code",[e._v("@TestConstructor")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-nestedtestconfiguration"}},[n("code",[e._v("@NestedTestConfiguration")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-junit-jupiter-enabledif"}},[n("code",[e._v("@EnabledIf")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-junit-jupiter-disabledif"}},[n("code",[e._v("@DisabledIf")])])])])]),e._v(" "),n("h5",{attrs:{id:"springjunitconfig"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#springjunitconfig"}},[e._v("#")]),e._v(" "),n("code",[e._v("@SpringJUnitConfig")])]),e._v(" "),n("p",[n("code",[e._v("@SpringJUnitConfig")]),e._v(" is a composed annotation that combines"),n("code",[e._v("@ExtendWith(SpringExtension.class)")]),e._v(" from JUnit Jupiter with "),n("code",[e._v("@ContextConfiguration")]),e._v(" from\nthe Spring TestContext Framework. It can be used at the class level as a drop-in\nreplacement for "),n("code",[e._v("@ContextConfiguration")]),e._v(". With regard to configuration options, the only\ndifference between "),n("code",[e._v("@ContextConfiguration")]),e._v(" and "),n("code",[e._v("@SpringJUnitConfig")]),e._v(" is that component\nclasses may be declared with the "),n("code",[e._v("value")]),e._v(" attribute in "),n("code",[e._v("@SpringJUnitConfig")]),e._v(".")]),e._v(" "),n("p",[e._v("The following example shows how to use the "),n("code",[e._v("@SpringJUnitConfig")]),e._v(" annotation to specify a\nconfiguration class:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(TestConfig.class) (1)\nclass ConfigurationClassJUnitJupiterSpringTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specify the configuration class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(TestConfig::class) (1)\nclass ConfigurationClassJUnitJupiterSpringTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specify the configuration class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("The following example shows how to use the "),n("code",[e._v("@SpringJUnitConfig")]),e._v(" annotation to specify the\nlocation of a configuration file:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(locations = "/test-config.xml") (1)\nclass XmlJUnitJupiterSpringTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specify the location of a configuration file.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(locations = ["/test-config.xml"]) (1)\nclass XmlJUnitJupiterSpringTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specify the location of a configuration file.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("See "),n("a",{attrs:{href:"#testcontext-ctx-management"}},[e._v("Context Management")]),e._v(" as well as the javadoc for"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/junit/jupiter/SpringJUnitConfig.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@SpringJUnitConfig")]),n("OutboundLink")],1),e._v("and "),n("code",[e._v("@ContextConfiguration")]),e._v(" for further details.")]),e._v(" "),n("h5",{attrs:{id:"springjunitwebconfig"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#springjunitwebconfig"}},[e._v("#")]),e._v(" "),n("code",[e._v("@SpringJUnitWebConfig")])]),e._v(" "),n("p",[n("code",[e._v("@SpringJUnitWebConfig")]),e._v(" is a composed annotation that combines"),n("code",[e._v("@ExtendWith(SpringExtension.class)")]),e._v(" from JUnit Jupiter with "),n("code",[e._v("@ContextConfiguration")]),e._v(" and"),n("code",[e._v("@WebAppConfiguration")]),e._v(" from the Spring TestContext Framework. You can use it at the class\nlevel as a drop-in replacement for "),n("code",[e._v("@ContextConfiguration")]),e._v(" and "),n("code",[e._v("@WebAppConfiguration")]),e._v(".\nWith regard to configuration options, the only difference between "),n("code",[e._v("@ContextConfiguration")]),e._v("and "),n("code",[e._v("@SpringJUnitWebConfig")]),e._v(" is that you can declare component classes by using the"),n("code",[e._v("value")]),e._v(" attribute in "),n("code",[e._v("@SpringJUnitWebConfig")]),e._v(". In addition, you can override the "),n("code",[e._v("value")]),e._v("attribute from "),n("code",[e._v("@WebAppConfiguration")]),e._v(" only by using the "),n("code",[e._v("resourcePath")]),e._v(" attribute in"),n("code",[e._v("@SpringJUnitWebConfig")]),e._v(".")]),e._v(" "),n("p",[e._v("The following example shows how to use the "),n("code",[e._v("@SpringJUnitWebConfig")]),e._v(" annotation to specify\na configuration class:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitWebConfig(TestConfig.class) (1)\nclass ConfigurationClassJUnitJupiterSpringWebTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specify the configuration class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitWebConfig(TestConfig::class) (1)\nclass ConfigurationClassJUnitJupiterSpringWebTests {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specify the configuration class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("The following example shows how to use the "),n("code",[e._v("@SpringJUnitWebConfig")]),e._v(" annotation to specify the\nlocation of a configuration file:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitWebConfig(locations = "/test-config.xml") (1)\nclass XmlJUnitJupiterSpringWebTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specify the location of a configuration file.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitWebConfig(locations = ["/test-config.xml"]) (1)\nclass XmlJUnitJupiterSpringWebTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specify the location of a configuration file.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("See "),n("a",{attrs:{href:"#testcontext-ctx-management"}},[e._v("Context Management")]),e._v(" as well as the javadoc for"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/junit/jupiter/web/SpringJUnitWebConfig.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@SpringJUnitWebConfig")]),n("OutboundLink")],1),e._v(","),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/ContextConfiguration.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@ContextConfiguration")]),n("OutboundLink")],1),e._v(", and"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/web/WebAppConfiguration.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@WebAppConfiguration")]),n("OutboundLink")],1),e._v("for further details.")]),e._v(" "),n("h5",{attrs:{id:"testconstructor"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#testconstructor"}},[e._v("#")]),e._v(" "),n("code",[e._v("@TestConstructor")])]),e._v(" "),n("p",[n("code",[e._v("@TestConstructor")]),e._v(" is a type-level annotation that is used to configure how the parameters\nof a test class constructor are autowired from components in the test’s"),n("code",[e._v("ApplicationContext")]),e._v(".")]),e._v(" "),n("p",[e._v("If "),n("code",[e._v("@TestConstructor")]),e._v(" is not present or meta-present on a test class, the default "),n("em",[e._v("test\nconstructor autowire mode")]),e._v(" will be used. See the tip below for details on how to change\nthe default mode. Note, however, that a local declaration of "),n("code",[e._v("@Autowired")]),e._v(" on a\nconstructor takes precedence over both "),n("code",[e._v("@TestConstructor")]),e._v(" and the default mode.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Changing the default test constructor autowire mode"),n("br"),n("br"),e._v("The default "),n("em",[e._v("test constructor autowire mode")]),e._v(" can be changed by setting the"),n("code",[e._v("spring.test.constructor.autowire.mode")]),e._v(" JVM system property to "),n("code",[e._v("all")]),e._v(". Alternatively, the"),n("br"),e._v("default mode may be set via the"),n("RouterLink",{attrs:{to:"/en/spring-framework/appendix.html#appendix-spring-properties"}},[n("code",[e._v("SpringProperties")])]),e._v(" mechanism."),n("br"),n("br"),e._v("As of Spring Framework 5.3, the default mode may also be configured as a"),n("a",{attrs:{href:"https://junit.org/junit5/docs/current/user-guide/#running-tests-config-params",target:"_blank",rel:"noopener noreferrer"}},[e._v("JUnit Platform configuration parameter"),n("OutboundLink")],1),e._v("."),n("br"),n("br"),e._v("If the "),n("code",[e._v("spring.test.constructor.autowire.mode")]),e._v(" property is not set, test class"),n("br"),e._v("constructors will not be automatically autowired.")],1)])]),e._v(" "),n("tbody")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("As of Spring Framework 5.2, "),n("code",[e._v("@TestConstructor")]),e._v(" is only supported in conjunction"),n("br"),e._v("with the "),n("code",[e._v("SpringExtension")]),e._v(" for use with JUnit Jupiter. Note that the "),n("code",[e._v("SpringExtension")]),e._v(" is"),n("br"),e._v("often automatically registered for you – for example, when using annotations such as"),n("code",[e._v("@SpringJUnitConfig")]),e._v(" and "),n("code",[e._v("@SpringJUnitWebConfig")]),e._v(" or various test-related annotations from"),n("br"),e._v("Spring Boot Test.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"nestedtestconfiguration"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#nestedtestconfiguration"}},[e._v("#")]),e._v(" "),n("code",[e._v("@NestedTestConfiguration")])]),e._v(" "),n("p",[n("code",[e._v("@NestedTestConfiguration")]),e._v(" is a type-level annotation that is used to configure how\nSpring test configuration annotations are processed within enclosing class hierarchies\nfor inner test classes.")]),e._v(" "),n("p",[e._v("If "),n("code",[e._v("@NestedTestConfiguration")]),e._v(" is not present or meta-present on a test class, in its\nsuper type hierarchy, or in its enclosing class hierarchy, the default "),n("em",[e._v("enclosing\nconfiguration inheritance mode")]),e._v(" will be used. See the tip below for details on how to\nchange the default mode.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Changing the default enclosing configuration inheritance mode"),n("br"),n("br"),e._v("The default "),n("em",[e._v("enclosing configuration inheritance mode")]),e._v(" is "),n("code",[e._v("INHERIT")]),e._v(", but it can be"),n("br"),e._v("changed by setting the "),n("code",[e._v("spring.test.enclosing.configuration")]),e._v(" JVM system property to"),n("code",[e._v("OVERRIDE")]),e._v(". Alternatively, the default mode may be set via the"),n("RouterLink",{attrs:{to:"/en/spring-framework/appendix.html#appendix-spring-properties"}},[n("code",[e._v("SpringProperties")])]),e._v(" mechanism.")],1)])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("The "),n("a",{attrs:{href:"#testcontext-framework"}},[e._v("Spring TestContext Framework")]),e._v(" honors "),n("code",[e._v("@NestedTestConfiguration")]),e._v(" semantics for the\nfollowing annotations.")]),e._v(" "),n("ul",[n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-bootstrapwith"}},[n("code",[e._v("@BootstrapWith")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-contextconfiguration"}},[n("code",[e._v("@ContextConfiguration")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-webappconfiguration"}},[n("code",[e._v("@WebAppConfiguration")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-contexthierarchy"}},[n("code",[e._v("@ContextHierarchy")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-activeprofiles"}},[n("code",[e._v("@ActiveProfiles")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-testpropertysource"}},[n("code",[e._v("@TestPropertySource")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-dynamicpropertysource"}},[n("code",[e._v("@DynamicPropertySource")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-dirtiescontext"}},[n("code",[e._v("@DirtiesContext")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-testexecutionlisteners"}},[n("code",[e._v("@TestExecutionListeners")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-recordapplicationevents"}},[n("code",[e._v("@RecordApplicationEvents")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-tx"}},[n("code",[e._v("@Transactional")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-commit"}},[n("code",[e._v("@Commit")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-rollback"}},[n("code",[e._v("@Rollback")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-sql"}},[n("code",[e._v("@Sql")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-sqlconfig"}},[n("code",[e._v("@SqlConfig")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-testing-annotation-sqlmergemode"}},[n("code",[e._v("@SqlMergeMode")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#integration-testing-annotations-testconstructor"}},[n("code",[e._v("@TestConstructor")])])])])]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("The use of "),n("code",[e._v("@NestedTestConfiguration")]),e._v(" typically only makes sense in conjunction"),n("br"),e._v("with "),n("code",[e._v("@Nested")]),e._v(" test classes in JUnit Jupiter; however, there may be other testing"),n("br"),e._v("frameworks with support for Spring and nested test classes that make use of this"),n("br"),e._v("annotation.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("See "),n("a",{attrs:{href:"#testcontext-junit-jupiter-nested-test-configuration"}},[n("code",[e._v("@Nested")]),e._v(" test class configuration")]),e._v(" for an example and further\ndetails.")]),e._v(" "),n("h5",{attrs:{id:"enabledif"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#enabledif"}},[e._v("#")]),e._v(" "),n("code",[e._v("@EnabledIf")])]),e._v(" "),n("p",[n("code",[e._v("@EnabledIf")]),e._v(" is used to signal that the annotated JUnit Jupiter test class or test method\nis enabled and should be run if the supplied "),n("code",[e._v("expression")]),e._v(" evaluates to "),n("code",[e._v("true")]),e._v(".\nSpecifically, if the expression evaluates to "),n("code",[e._v("Boolean.TRUE")]),e._v(" or a "),n("code",[e._v("String")]),e._v(" equal to "),n("code",[e._v("true")]),e._v("(ignoring case), the test is enabled. When applied at the class level, all test methods\nwithin that class are automatically enabled by default as well.")]),e._v(" "),n("p",[e._v("Expressions can be any of the following:")]),e._v(" "),n("ul",[n("li",[n("p",[n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#expressions"}},[e._v("Spring Expression Language")]),e._v(" (SpEL) expression. For example:"),n("code",[e._v("@EnabledIf(\"#{systemProperties['os.name'].toLowerCase().contains('mac')}\")")])],1)]),e._v(" "),n("li",[n("p",[e._v("Placeholder for a property available in the Spring "),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#beans-environment"}},[n("code",[e._v("Environment")])]),e._v(".\nFor example: "),n("code",[e._v('@EnabledIf("${smoke.tests.enabled}")')])],1)]),e._v(" "),n("li",[n("p",[e._v("Text literal. For example: "),n("code",[e._v('@EnabledIf("true")')])])])]),e._v(" "),n("p",[e._v("Note, however, that a text literal that is not the result of dynamic resolution of a\nproperty placeholder is of zero practical value, since "),n("code",[e._v('@EnabledIf("false")')]),e._v(" is\nequivalent to "),n("code",[e._v("@Disabled")]),e._v(" and "),n("code",[e._v('@EnabledIf("true")')]),e._v(" is logically meaningless.")]),e._v(" "),n("p",[e._v("You can use "),n("code",[e._v("@EnabledIf")]),e._v(" as a meta-annotation to create custom composed annotations. For\nexample, you can create a custom "),n("code",[e._v("@EnabledOnMac")]),e._v(" annotation as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Target({ElementType.TYPE, ElementType.METHOD})\n@Retention(RetentionPolicy.RUNTIME)\n@EnabledIf(\n expression = \"#{systemProperties['os.name'].toLowerCase().contains('mac')}\",\n reason = \"Enabled on Mac OS\"\n)\npublic @interface EnabledOnMac {}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)\n@Retention(AnnotationRetention.RUNTIME)\n@EnabledIf(\n expression = \"#{systemProperties['os.name'].toLowerCase().contains('mac')}\",\n reason = \"Enabled on Mac OS\"\n)\nannotation class EnabledOnMac {}\n")])])]),n("h5",{attrs:{id:"disabledif"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#disabledif"}},[e._v("#")]),e._v(" "),n("code",[e._v("@DisabledIf")])]),e._v(" "),n("p",[n("code",[e._v("@DisabledIf")]),e._v(" is used to signal that the annotated JUnit Jupiter test class or test\nmethod is disabled and should not be run if the supplied "),n("code",[e._v("expression")]),e._v(" evaluates to"),n("code",[e._v("true")]),e._v(". Specifically, if the expression evaluates to "),n("code",[e._v("Boolean.TRUE")]),e._v(" or a "),n("code",[e._v("String")]),e._v(" equal\nto "),n("code",[e._v("true")]),e._v(" (ignoring case), the test is disabled. When applied at the class level, all\ntest methods within that class are automatically disabled as well.")]),e._v(" "),n("p",[e._v("Expressions can be any of the following:")]),e._v(" "),n("ul",[n("li",[n("p",[n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#expressions"}},[e._v("Spring Expression Language")]),e._v(" (SpEL) expression. For example:"),n("code",[e._v("@DisabledIf(\"#{systemProperties['os.name'].toLowerCase().contains('mac')}\")")])],1)]),e._v(" "),n("li",[n("p",[e._v("Placeholder for a property available in the Spring "),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#beans-environment"}},[n("code",[e._v("Environment")])]),e._v(".\nFor example: "),n("code",[e._v('@DisabledIf("${smoke.tests.disabled}")')])],1)]),e._v(" "),n("li",[n("p",[e._v("Text literal. For example: "),n("code",[e._v('@DisabledIf("true")')])])])]),e._v(" "),n("p",[e._v("Note, however, that a text literal that is not the result of dynamic resolution of a\nproperty placeholder is of zero practical value, since "),n("code",[e._v('@DisabledIf("true")')]),e._v(" is\nequivalent to "),n("code",[e._v("@Disabled")]),e._v(" and "),n("code",[e._v('@DisabledIf("false")')]),e._v(" is logically meaningless.")]),e._v(" "),n("p",[e._v("You can use "),n("code",[e._v("@DisabledIf")]),e._v(" as a meta-annotation to create custom composed annotations. For\nexample, you can create a custom "),n("code",[e._v("@DisabledOnMac")]),e._v(" annotation as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Target({ElementType.TYPE, ElementType.METHOD})\n@Retention(RetentionPolicy.RUNTIME)\n@DisabledIf(\n expression = \"#{systemProperties['os.name'].toLowerCase().contains('mac')}\",\n reason = \"Disabled on Mac OS\"\n)\npublic @interface DisabledOnMac {}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)\n@Retention(AnnotationRetention.RUNTIME)\n@DisabledIf(\n expression = \"#{systemProperties['os.name'].toLowerCase().contains('mac')}\",\n reason = \"Disabled on Mac OS\"\n)\nannotation class DisabledOnMac {}\n")])])]),n("h4",{attrs:{id:"_3-4-5-meta-annotation-support-for-testing"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-4-5-meta-annotation-support-for-testing"}},[e._v("#")]),e._v(" 3.4.5. Meta-Annotation Support for Testing")]),e._v(" "),n("p",[e._v("You can use most test-related annotations as"),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#beans-meta-annotations"}},[e._v("meta-annotations")]),e._v(" to create custom composed\nannotations and reduce configuration duplication across a test suite.")],1),e._v(" "),n("p",[e._v("You can use each of the following as a meta-annotation in conjunction with the"),n("a",{attrs:{href:"#testcontext-framework"}},[e._v("TestContext framework")]),e._v(".")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("@BootstrapWith")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@ContextConfiguration")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@ContextHierarchy")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@ActiveProfiles")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@TestPropertySource")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@DirtiesContext")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@WebAppConfiguration")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@TestExecutionListeners")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Transactional")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@BeforeTransaction")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@AfterTransaction")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Commit")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Rollback")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Sql")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@SqlConfig")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@SqlMergeMode")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@SqlGroup")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Repeat")]),e._v(" "),n("em",[e._v("(only supported on JUnit 4)")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@Timed")]),e._v(" "),n("em",[e._v("(only supported on JUnit 4)")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@IfProfileValue")]),e._v(" "),n("em",[e._v("(only supported on JUnit 4)")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@ProfileValueSourceConfiguration")]),e._v(" "),n("em",[e._v("(only supported on JUnit 4)")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@SpringJUnitConfig")]),e._v(" "),n("em",[e._v("(only supported on JUnit Jupiter)")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@SpringJUnitWebConfig")]),e._v(" "),n("em",[e._v("(only supported on JUnit Jupiter)")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@TestConstructor")]),e._v(" "),n("em",[e._v("(only supported on JUnit Jupiter)")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@NestedTestConfiguration")]),e._v(" "),n("em",[e._v("(only supported on JUnit Jupiter)")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@EnabledIf")]),e._v(" "),n("em",[e._v("(only supported on JUnit Jupiter)")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@DisabledIf")]),e._v(" "),n("em",[e._v("(only supported on JUnit Jupiter)")])])])]),e._v(" "),n("p",[e._v("Consider the following example:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@RunWith(SpringRunner.class)\n@ContextConfiguration({"/app-config.xml", "/test-data-access-config.xml"})\n@ActiveProfiles("dev")\n@Transactional\npublic class OrderRepositoryTests { }\n\n@RunWith(SpringRunner.class)\n@ContextConfiguration({"/app-config.xml", "/test-data-access-config.xml"})\n@ActiveProfiles("dev")\n@Transactional\npublic class UserRepositoryTests { }\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@RunWith(SpringRunner::class)\n@ContextConfiguration("/app-config.xml", "/test-data-access-config.xml")\n@ActiveProfiles("dev")\n@Transactional\nclass OrderRepositoryTests { }\n\n@RunWith(SpringRunner::class)\n@ContextConfiguration("/app-config.xml", "/test-data-access-config.xml")\n@ActiveProfiles("dev")\n@Transactional\nclass UserRepositoryTests { }\n')])])]),n("p",[e._v("If we discover that we are repeating the preceding configuration across our JUnit 4-based\ntest suite, we can reduce the duplication by introducing a custom composed annotation\nthat centralizes the common test configuration for Spring, as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Target(ElementType.TYPE)\n@Retention(RetentionPolicy.RUNTIME)\n@ContextConfiguration({"/app-config.xml", "/test-data-access-config.xml"})\n@ActiveProfiles("dev")\n@Transactional\npublic @interface TransactionalDevTestConfig { }\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Target(AnnotationTarget.TYPE)\n@Retention(AnnotationRetention.RUNTIME)\n@ContextConfiguration("/app-config.xml", "/test-data-access-config.xml")\n@ActiveProfiles("dev")\n@Transactional\nannotation class TransactionalDevTestConfig { }\n')])])]),n("p",[e._v("Then we can use our custom "),n("code",[e._v("@TransactionalDevTestConfig")]),e._v(" annotation to simplify the\nconfiguration of individual JUnit 4 based test classes, as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@RunWith(SpringRunner.class)\n@TransactionalDevTestConfig\npublic class OrderRepositoryTests { }\n\n@RunWith(SpringRunner.class)\n@TransactionalDevTestConfig\npublic class UserRepositoryTests { }\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@RunWith(SpringRunner::class)\n@TransactionalDevTestConfig\nclass OrderRepositoryTests\n\n@RunWith(SpringRunner::class)\n@TransactionalDevTestConfig\nclass UserRepositoryTests\n")])])]),n("p",[e._v("If we write tests that use JUnit Jupiter, we can reduce code duplication even further,\nsince annotations in JUnit 5 can also be used as meta-annotations. Consider the following\nexample:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n@ContextConfiguration({"/app-config.xml", "/test-data-access-config.xml"})\n@ActiveProfiles("dev")\n@Transactional\nclass OrderRepositoryTests { }\n\n@ExtendWith(SpringExtension.class)\n@ContextConfiguration({"/app-config.xml", "/test-data-access-config.xml"})\n@ActiveProfiles("dev")\n@Transactional\nclass UserRepositoryTests { }\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n@ContextConfiguration("/app-config.xml", "/test-data-access-config.xml")\n@ActiveProfiles("dev")\n@Transactional\nclass OrderRepositoryTests { }\n\n@ExtendWith(SpringExtension::class)\n@ContextConfiguration("/app-config.xml", "/test-data-access-config.xml")\n@ActiveProfiles("dev")\n@Transactional\nclass UserRepositoryTests { }\n')])])]),n("p",[e._v("If we discover that we are repeating the preceding configuration across our JUnit\nJupiter-based test suite, we can reduce the duplication by introducing a custom composed\nannotation that centralizes the common test configuration for Spring and JUnit Jupiter,\nas follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Target(ElementType.TYPE)\n@Retention(RetentionPolicy.RUNTIME)\n@ExtendWith(SpringExtension.class)\n@ContextConfiguration({"/app-config.xml", "/test-data-access-config.xml"})\n@ActiveProfiles("dev")\n@Transactional\npublic @interface TransactionalDevTestConfig { }\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Target(AnnotationTarget.TYPE)\n@Retention(AnnotationRetention.RUNTIME)\n@ExtendWith(SpringExtension::class)\n@ContextConfiguration("/app-config.xml", "/test-data-access-config.xml")\n@ActiveProfiles("dev")\n@Transactional\nannotation class TransactionalDevTestConfig { }\n')])])]),n("p",[e._v("Then we can use our custom "),n("code",[e._v("@TransactionalDevTestConfig")]),e._v(" annotation to simplify the\nconfiguration of individual JUnit Jupiter based test classes, as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@TransactionalDevTestConfig\nclass OrderRepositoryTests { }\n\n@TransactionalDevTestConfig\nclass UserRepositoryTests { }\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@TransactionalDevTestConfig\nclass OrderRepositoryTests { }\n\n@TransactionalDevTestConfig\nclass UserRepositoryTests { }\n")])])]),n("p",[e._v("Since JUnit Jupiter supports the use of "),n("code",[e._v("@Test")]),e._v(", "),n("code",[e._v("@RepeatedTest")]),e._v(", "),n("code",[e._v("ParameterizedTest")]),e._v(",\nand others as meta-annotations, you can also create custom composed annotations at the\ntest method level. For example, if we wish to create a composed annotation that combines\nthe "),n("code",[e._v("@Test")]),e._v(" and "),n("code",[e._v("@Tag")]),e._v(" annotations from JUnit Jupiter with the "),n("code",[e._v("@Transactional")]),e._v("annotation from Spring, we could create an "),n("code",[e._v("@TransactionalIntegrationTest")]),e._v(" annotation, as\nfollows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Target(ElementType.METHOD)\n@Retention(RetentionPolicy.RUNTIME)\n@Transactional\n@Tag("integration-test") // org.junit.jupiter.api.Tag\n@Test // org.junit.jupiter.api.Test\npublic @interface TransactionalIntegrationTest { }\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Target(AnnotationTarget.TYPE)\n@Retention(AnnotationRetention.RUNTIME)\n@Transactional\n@Tag("integration-test") // org.junit.jupiter.api.Tag\n@Test // org.junit.jupiter.api.Test\nannotation class TransactionalIntegrationTest { }\n')])])]),n("p",[e._v("Then we can use our custom "),n("code",[e._v("@TransactionalIntegrationTest")]),e._v(" annotation to simplify the\nconfiguration of individual JUnit Jupiter based test methods, as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@TransactionalIntegrationTest\nvoid saveOrder() { }\n\n@TransactionalIntegrationTest\nvoid deleteOrder() { }\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@TransactionalIntegrationTest\nfun saveOrder() { }\n\n@TransactionalIntegrationTest\nfun deleteOrder() { }\n")])])]),n("p",[e._v("For further details, see the"),n("a",{attrs:{href:"https://github.com/spring-projects/spring-framework/wiki/Spring-Annotation-Programming-Model",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Annotation Programming Model"),n("OutboundLink")],1),e._v("wiki page.")]),e._v(" "),n("h3",{attrs:{id:"_3-5-spring-testcontext-framework"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-spring-testcontext-framework"}},[e._v("#")]),e._v(" 3.5. Spring TestContext Framework")]),e._v(" "),n("p",[e._v("The Spring TestContext Framework (located in the "),n("code",[e._v("org.springframework.test.context")]),e._v("package) provides generic, annotation-driven unit and integration testing support that is\nagnostic of the testing framework in use. The TestContext framework also places a great\ndeal of importance on convention over configuration, with reasonable defaults that you\ncan override through annotation-based configuration.")]),e._v(" "),n("p",[e._v("In addition to generic testing infrastructure, the TestContext framework provides\nexplicit support for JUnit 4, JUnit Jupiter (AKA JUnit 5), and TestNG. For JUnit 4 and\nTestNG, Spring provides "),n("code",[e._v("abstract")]),e._v(" support classes. Furthermore, Spring provides a custom\nJUnit "),n("code",[e._v("Runner")]),e._v(" and custom JUnit "),n("code",[e._v("Rules")]),e._v(" for JUnit 4 and a custom "),n("code",[e._v("Extension")]),e._v(" for JUnit\nJupiter that let you write so-called POJO test classes. POJO test classes are not\nrequired to extend a particular class hierarchy, such as the "),n("code",[e._v("abstract")]),e._v(" support classes.")]),e._v(" "),n("p",[e._v("The following section provides an overview of the internals of the TestContext framework.\nIf you are interested only in using the framework and are not interested in extending it\nwith your own custom listeners or custom loaders, feel free to go directly to the\nconfiguration ("),n("a",{attrs:{href:"#testcontext-ctx-management"}},[e._v("context management")]),e._v(","),n("a",{attrs:{href:"#testcontext-fixture-di"}},[e._v("dependency injection")]),e._v(", "),n("a",{attrs:{href:"#testcontext-tx"}},[e._v("transaction\nmanagement")]),e._v("), "),n("a",{attrs:{href:"#testcontext-support-classes"}},[e._v("support classes")]),e._v(", and"),n("a",{attrs:{href:"#integration-testing-annotations"}},[e._v("annotation support")]),e._v(" sections.")]),e._v(" "),n("h4",{attrs:{id:"_3-5-1-key-abstractions"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-1-key-abstractions"}},[e._v("#")]),e._v(" 3.5.1. Key Abstractions")]),e._v(" "),n("p",[e._v("The core of the framework consists of the "),n("code",[e._v("TestContextManager")]),e._v(" class and the"),n("code",[e._v("TestContext")]),e._v(", "),n("code",[e._v("TestExecutionListener")]),e._v(", and "),n("code",[e._v("SmartContextLoader")]),e._v(" interfaces. A"),n("code",[e._v("TestContextManager")]),e._v(" is created for each test class (for example, for the execution of\nall test methods within a single test class in JUnit Jupiter). The "),n("code",[e._v("TestContextManager")]),e._v(",\nin turn, manages a "),n("code",[e._v("TestContext")]),e._v(" that holds the context of the current test. The"),n("code",[e._v("TestContextManager")]),e._v(" also updates the state of the "),n("code",[e._v("TestContext")]),e._v(" as the test progresses\nand delegates to "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations, which instrument the actual\ntest execution by providing dependency injection, managing transactions, and so on. A"),n("code",[e._v("SmartContextLoader")]),e._v(" is responsible for loading an "),n("code",[e._v("ApplicationContext")]),e._v(" for a given test\nclass. See the "),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/package-summary.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("javadoc"),n("OutboundLink")],1),e._v(" and the\nSpring test suite for further information and examples of various implementations.")]),e._v(" "),n("h5",{attrs:{id:"testcontext"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#testcontext"}},[e._v("#")]),e._v(" "),n("code",[e._v("TestContext")])]),e._v(" "),n("p",[n("code",[e._v("TestContext")]),e._v(" encapsulates the context in which a test is run (agnostic of the\nactual testing framework in use) and provides context management and caching support for\nthe test instance for which it is responsible. The "),n("code",[e._v("TestContext")]),e._v(" also delegates to a"),n("code",[e._v("SmartContextLoader")]),e._v(" to load an "),n("code",[e._v("ApplicationContext")]),e._v(" if requested.")]),e._v(" "),n("h5",{attrs:{id:"testcontextmanager"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#testcontextmanager"}},[e._v("#")]),e._v(" "),n("code",[e._v("TestContextManager")])]),e._v(" "),n("p",[n("code",[e._v("TestContextManager")]),e._v(" is the main entry point into the Spring TestContext Framework and is\nresponsible for managing a single "),n("code",[e._v("TestContext")]),e._v(" and signaling events to each registered"),n("code",[e._v("TestExecutionListener")]),e._v(" at well-defined test execution points:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("Prior to any “before class” or “before all” methods of a particular testing framework.")])]),e._v(" "),n("li",[n("p",[e._v("Test instance post-processing.")])]),e._v(" "),n("li",[n("p",[e._v("Prior to any “before” or “before each” methods of a particular testing framework.")])]),e._v(" "),n("li",[n("p",[e._v("Immediately before execution of the test method but after test setup.")])]),e._v(" "),n("li",[n("p",[e._v("Immediately after execution of the test method but before test tear down.")])]),e._v(" "),n("li",[n("p",[e._v("After any “after” or “after each” methods of a particular testing framework.")])]),e._v(" "),n("li",[n("p",[e._v("After any “after class” or “after all” methods of a particular testing framework.")])])]),e._v(" "),n("h5",{attrs:{id:"testexecutionlistener"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#testexecutionlistener"}},[e._v("#")]),e._v(" "),n("code",[e._v("TestExecutionListener")])]),e._v(" "),n("p",[n("code",[e._v("TestExecutionListener")]),e._v(" defines the API for reacting to test-execution events published by\nthe "),n("code",[e._v("TestContextManager")]),e._v(" with which the listener is registered. See "),n("a",{attrs:{href:"#testcontext-tel-config"}},[n("code",[e._v("TestExecutionListener")]),e._v(" Configuration")]),e._v(".")]),e._v(" "),n("h5",{attrs:{id:"context-loaders"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#context-loaders"}},[e._v("#")]),e._v(" Context Loaders")]),e._v(" "),n("p",[n("code",[e._v("ContextLoader")]),e._v(" is a strategy interface for loading an "),n("code",[e._v("ApplicationContext")]),e._v(" for an\nintegration test managed by the Spring TestContext Framework. You should implement"),n("code",[e._v("SmartContextLoader")]),e._v(" instead of this interface to provide support for component classes,\nactive bean definition profiles, test property sources, context hierarchies, and"),n("code",[e._v("WebApplicationContext")]),e._v(" support.")]),e._v(" "),n("p",[n("code",[e._v("SmartContextLoader")]),e._v(" is an extension of the "),n("code",[e._v("ContextLoader")]),e._v(" interface that supersedes the\noriginal minimal "),n("code",[e._v("ContextLoader")]),e._v(" SPI. Specifically, a "),n("code",[e._v("SmartContextLoader")]),e._v(" can choose to\nprocess resource locations, component classes, or context initializers. Furthermore, a"),n("code",[e._v("SmartContextLoader")]),e._v(" can set active bean definition profiles and test property sources in\nthe context that it loads.")]),e._v(" "),n("p",[e._v("Spring provides the following implementations:")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("DelegatingSmartContextLoader")]),e._v(": One of two default loaders, it delegates internally to\nan "),n("code",[e._v("AnnotationConfigContextLoader")]),e._v(", a "),n("code",[e._v("GenericXmlContextLoader")]),e._v(", or a"),n("code",[e._v("GenericGroovyXmlContextLoader")]),e._v(", depending either on the configuration declared for the\ntest class or on the presence of default locations or default configuration classes.\nGroovy support is enabled only if Groovy is on the classpath.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("WebDelegatingSmartContextLoader")]),e._v(": One of two default loaders, it delegates internally\nto an "),n("code",[e._v("AnnotationConfigWebContextLoader")]),e._v(", a "),n("code",[e._v("GenericXmlWebContextLoader")]),e._v(", or a"),n("code",[e._v("GenericGroovyXmlWebContextLoader")]),e._v(", depending either on the configuration declared for\nthe test class or on the presence of default locations or default configuration\nclasses. A web "),n("code",[e._v("ContextLoader")]),e._v(" is used only if "),n("code",[e._v("@WebAppConfiguration")]),e._v(" is present on the\ntest class. Groovy support is enabled only if Groovy is on the classpath.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("AnnotationConfigContextLoader")]),e._v(": Loads a standard "),n("code",[e._v("ApplicationContext")]),e._v(" from component\nclasses.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("AnnotationConfigWebContextLoader")]),e._v(": Loads a "),n("code",[e._v("WebApplicationContext")]),e._v(" from component\nclasses.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("GenericGroovyXmlContextLoader")]),e._v(": Loads a standard "),n("code",[e._v("ApplicationContext")]),e._v(" from resource\nlocations that are either Groovy scripts or XML configuration files.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("GenericGroovyXmlWebContextLoader")]),e._v(": Loads a "),n("code",[e._v("WebApplicationContext")]),e._v(" from resource\nlocations that are either Groovy scripts or XML configuration files.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("GenericXmlContextLoader")]),e._v(": Loads a standard "),n("code",[e._v("ApplicationContext")]),e._v(" from XML resource\nlocations.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("GenericXmlWebContextLoader")]),e._v(": Loads a "),n("code",[e._v("WebApplicationContext")]),e._v(" from XML resource\nlocations.")])])]),e._v(" "),n("h4",{attrs:{id:"_3-5-2-bootstrapping-the-testcontext-framework"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-2-bootstrapping-the-testcontext-framework"}},[e._v("#")]),e._v(" 3.5.2. Bootstrapping the TestContext Framework")]),e._v(" "),n("p",[e._v("The default configuration for the internals of the Spring TestContext Framework is\nsufficient for all common use cases. However, there are times when a development team or\nthird party framework would like to change the default "),n("code",[e._v("ContextLoader")]),e._v(", implement a\ncustom "),n("code",[e._v("TestContext")]),e._v(" or "),n("code",[e._v("ContextCache")]),e._v(", augment the default sets of"),n("code",[e._v("ContextCustomizerFactory")]),e._v(" and "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations, and so on. For\nsuch low-level control over how the TestContext framework operates, Spring provides a\nbootstrapping strategy.")]),e._v(" "),n("p",[n("code",[e._v("TestContextBootstrapper")]),e._v(" defines the SPI for bootstrapping the TestContext framework. A"),n("code",[e._v("TestContextBootstrapper")]),e._v(" is used by the "),n("code",[e._v("TestContextManager")]),e._v(" to load the"),n("code",[e._v("TestExecutionListener")]),e._v(" implementations for the current test and to build the"),n("code",[e._v("TestContext")]),e._v(" that it manages. You can configure a custom bootstrapping strategy for a\ntest class (or test class hierarchy) by using "),n("code",[e._v("@BootstrapWith")]),e._v(", either directly or as a\nmeta-annotation. If a bootstrapper is not explicitly configured by using"),n("code",[e._v("@BootstrapWith")]),e._v(", either the "),n("code",[e._v("DefaultTestContextBootstrapper")]),e._v(" or the"),n("code",[e._v("WebTestContextBootstrapper")]),e._v(" is used, depending on the presence of "),n("code",[e._v("@WebAppConfiguration")]),e._v(".")]),e._v(" "),n("p",[e._v("Since the "),n("code",[e._v("TestContextBootstrapper")]),e._v(" SPI is likely to change in the future (to accommodate\nnew requirements), we strongly encourage implementers not to implement this interface\ndirectly but rather to extend "),n("code",[e._v("AbstractTestContextBootstrapper")]),e._v(" or one of its concrete\nsubclasses instead.")]),e._v(" "),n("h4",{attrs:{id:"_3-5-3-testexecutionlistener-configuration"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-3-testexecutionlistener-configuration"}},[e._v("#")]),e._v(" 3.5.3. "),n("code",[e._v("TestExecutionListener")]),e._v(" Configuration")]),e._v(" "),n("p",[e._v("Spring provides the following "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations that are registered\nby default, exactly in the following order:")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("ServletTestExecutionListener")]),e._v(": Configures Servlet API mocks for a"),n("code",[e._v("WebApplicationContext")]),e._v(".")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("DirtiesContextBeforeModesTestExecutionListener")]),e._v(": Handles the "),n("code",[e._v("@DirtiesContext")]),e._v("annotation for “before” modes.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("ApplicationEventsTestExecutionListener")]),e._v(": Provides support for"),n("a",{attrs:{href:"#testcontext-application-events"}},[n("code",[e._v("ApplicationEvents")])]),e._v(".")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("DependencyInjectionTestExecutionListener")]),e._v(": Provides dependency injection for the test\ninstance.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("DirtiesContextTestExecutionListener")]),e._v(": Handles the "),n("code",[e._v("@DirtiesContext")]),e._v(" annotation for\n“after” modes.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("TransactionalTestExecutionListener")]),e._v(": Provides transactional test execution with\ndefault rollback semantics.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("SqlScriptsTestExecutionListener")]),e._v(": Runs SQL scripts configured by using the "),n("code",[e._v("@Sql")]),e._v("annotation.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("EventPublishingTestExecutionListener")]),e._v(": Publishes test execution events to the test’s"),n("code",[e._v("ApplicationContext")]),e._v(" (see "),n("a",{attrs:{href:"#testcontext-test-execution-events"}},[e._v("Test Execution Events")]),e._v(").")])])]),e._v(" "),n("h5",{attrs:{id:"registering-testexecutionlistener-implementations"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#registering-testexecutionlistener-implementations"}},[e._v("#")]),e._v(" Registering "),n("code",[e._v("TestExecutionListener")]),e._v(" Implementations")]),e._v(" "),n("p",[e._v("You can register "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations for a test class and its\nsubclasses by using the "),n("code",[e._v("@TestExecutionListeners")]),e._v(" annotation. See"),n("a",{attrs:{href:"#integration-testing-annotations"}},[e._v("annotation support")]),e._v(" and the javadoc for"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/TestExecutionListeners.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@TestExecutionListeners")]),n("OutboundLink")],1),e._v("for details and examples.")]),e._v(" "),n("h5",{attrs:{id:"automatic-discovery-of-default-testexecutionlistener-implementations"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#automatic-discovery-of-default-testexecutionlistener-implementations"}},[e._v("#")]),e._v(" Automatic Discovery of Default "),n("code",[e._v("TestExecutionListener")]),e._v(" Implementations")]),e._v(" "),n("p",[e._v("Registering "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations by using "),n("code",[e._v("@TestExecutionListeners")]),e._v(" is\nsuitable for custom listeners that are used in limited testing scenarios. However, it can\nbecome cumbersome if a custom listener needs to be used across an entire test suite. This\nissue is addressed through support for automatic discovery of default"),n("code",[e._v("TestExecutionListener")]),e._v(" implementations through the "),n("code",[e._v("SpringFactoriesLoader")]),e._v(" mechanism.")]),e._v(" "),n("p",[e._v("Specifically, the "),n("code",[e._v("spring-test")]),e._v(" module declares all core default "),n("code",[e._v("TestExecutionListener")]),e._v("implementations under the "),n("code",[e._v("org.springframework.test.context.TestExecutionListener")]),e._v(" key in\nits "),n("code",[e._v("META-INF/spring.factories")]),e._v(" properties file. Third-party frameworks and developers\ncan contribute their own "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations to the list of default\nlisteners in the same manner through their own "),n("code",[e._v("META-INF/spring.factories")]),e._v(" properties\nfile.")]),e._v(" "),n("h5",{attrs:{id:"ordering-testexecutionlistener-implementations"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#ordering-testexecutionlistener-implementations"}},[e._v("#")]),e._v(" Ordering "),n("code",[e._v("TestExecutionListener")]),e._v(" Implementations")]),e._v(" "),n("p",[e._v("When the TestContext framework discovers default "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations\nthrough the "),n("a",{attrs:{href:"#testcontext-tel-config-automatic-discovery"}},[e._v("aforementioned")]),n("code",[e._v("SpringFactoriesLoader")]),e._v(" mechanism, the instantiated listeners are sorted by using\nSpring’s "),n("code",[e._v("AnnotationAwareOrderComparator")]),e._v(", which honors Spring’s "),n("code",[e._v("Ordered")]),e._v(" interface and"),n("code",[e._v("@Order")]),e._v(" annotation for ordering. "),n("code",[e._v("AbstractTestExecutionListener")]),e._v(" and all default"),n("code",[e._v("TestExecutionListener")]),e._v(" implementations provided by Spring implement "),n("code",[e._v("Ordered")]),e._v(" with\nappropriate values. Third-party frameworks and developers should therefore make sure that\ntheir default "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations are registered in the proper order\nby implementing "),n("code",[e._v("Ordered")]),e._v(" or declaring "),n("code",[e._v("@Order")]),e._v(". See the javadoc for the "),n("code",[e._v("getOrder()")]),e._v("methods of the core default "),n("code",[e._v("TestExecutionListener")]),e._v(" implementations for details on what\nvalues are assigned to each core listener.")]),e._v(" "),n("h5",{attrs:{id:"merging-testexecutionlistener-implementations"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#merging-testexecutionlistener-implementations"}},[e._v("#")]),e._v(" Merging "),n("code",[e._v("TestExecutionListener")]),e._v(" Implementations")]),e._v(" "),n("p",[e._v("If a custom "),n("code",[e._v("TestExecutionListener")]),e._v(" is registered via "),n("code",[e._v("@TestExecutionListeners")]),e._v(", the\ndefault listeners are not registered. In most common testing scenarios, this effectively\nforces the developer to manually declare all default listeners in addition to any custom\nlisteners. The following listing demonstrates this style of configuration:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ContextConfiguration\n@TestExecutionListeners({\n MyCustomTestExecutionListener.class,\n ServletTestExecutionListener.class,\n DirtiesContextBeforeModesTestExecutionListener.class,\n DependencyInjectionTestExecutionListener.class,\n DirtiesContextTestExecutionListener.class,\n TransactionalTestExecutionListener.class,\n SqlScriptsTestExecutionListener.class\n})\nclass MyTest {\n // class body...\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ContextConfiguration\n@TestExecutionListeners(\n MyCustomTestExecutionListener::class,\n ServletTestExecutionListener::class,\n DirtiesContextBeforeModesTestExecutionListener::class,\n DependencyInjectionTestExecutionListener::class,\n DirtiesContextTestExecutionListener::class,\n TransactionalTestExecutionListener::class,\n SqlScriptsTestExecutionListener::class\n)\nclass MyTest {\n // class body...\n}\n")])])]),n("p",[e._v("The challenge with this approach is that it requires that the developer know exactly\nwhich listeners are registered by default. Moreover, the set of default listeners can\nchange from release to release — for example, "),n("code",[e._v("SqlScriptsTestExecutionListener")]),e._v(" was\nintroduced in Spring Framework 4.1, and "),n("code",[e._v("DirtiesContextBeforeModesTestExecutionListener")]),e._v("was introduced in Spring Framework 4.2. Furthermore, third-party frameworks like Spring\nBoot and Spring Security register their own default "),n("code",[e._v("TestExecutionListener")]),e._v("implementations by using the aforementioned "),n("a",{attrs:{href:"#testcontext-tel-config-automatic-discovery"}},[e._v("automatic discovery mechanism")]),e._v(".")]),e._v(" "),n("p",[e._v("To avoid having to be aware of and re-declare all default listeners, you can set the"),n("code",[e._v("mergeMode")]),e._v(" attribute of "),n("code",[e._v("@TestExecutionListeners")]),e._v(" to "),n("code",[e._v("MergeMode.MERGE_WITH_DEFAULTS")]),e._v("."),n("code",[e._v("MERGE_WITH_DEFAULTS")]),e._v(" indicates that locally declared listeners should be merged with the\ndefault listeners. The merging algorithm ensures that duplicates are removed from the\nlist and that the resulting set of merged listeners is sorted according to the semantics\nof "),n("code",[e._v("AnnotationAwareOrderComparator")]),e._v(", as described in "),n("a",{attrs:{href:"#testcontext-tel-config-ordering"}},[e._v("Ordering "),n("code",[e._v("TestExecutionListener")]),e._v(" Implementations")]),e._v(".\nIf a listener implements "),n("code",[e._v("Ordered")]),e._v(" or is annotated with "),n("code",[e._v("@Order")]),e._v(", it can influence the\nposition in which it is merged with the defaults. Otherwise, locally declared listeners\nare appended to the list of default listeners when merged.")]),e._v(" "),n("p",[e._v("For example, if the "),n("code",[e._v("MyCustomTestExecutionListener")]),e._v(" class in the previous example\nconfigures its "),n("code",[e._v("order")]),e._v(" value (for example, "),n("code",[e._v("500")]),e._v(") to be less than the order of the"),n("code",[e._v("ServletTestExecutionListener")]),e._v(" (which happens to be "),n("code",[e._v("1000")]),e._v("), the"),n("code",[e._v("MyCustomTestExecutionListener")]),e._v(" can then be automatically merged with the list of\ndefaults in front of the "),n("code",[e._v("ServletTestExecutionListener")]),e._v(", and the previous example could\nbe replaced with the following:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ContextConfiguration\n@TestExecutionListeners(\n listeners = MyCustomTestExecutionListener.class,\n mergeMode = MERGE_WITH_DEFAULTS\n)\nclass MyTest {\n // class body...\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ContextConfiguration\n@TestExecutionListeners(\n listeners = [MyCustomTestExecutionListener::class],\n mergeMode = MERGE_WITH_DEFAULTS\n)\nclass MyTest {\n // class body...\n}\n")])])]),n("h4",{attrs:{id:"_3-5-4-application-events"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-4-application-events"}},[e._v("#")]),e._v(" 3.5.4. Application Events")]),e._v(" "),n("p",[e._v("Since Spring Framework 5.3.3, the TestContext framework provides support for recording"),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#context-functionality-events"}},[e._v("application events")]),e._v(" published in the"),n("code",[e._v("ApplicationContext")]),e._v(" so that assertions can be performed against those events within\ntests. All events published during the execution of a single test are made available via\nthe "),n("code",[e._v("ApplicationEvents")]),e._v(" API which allows you to process the events as a"),n("code",[e._v("java.util.Stream")]),e._v(".")],1),e._v(" "),n("p",[e._v("To use "),n("code",[e._v("ApplicationEvents")]),e._v(" in your tests, do the following.")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("Ensure that your test class is annotated or meta-annotated with"),n("a",{attrs:{href:"#spring-testing-annotation-recordapplicationevents"}},[n("code",[e._v("@RecordApplicationEvents")])]),e._v(".")])]),e._v(" "),n("li",[n("p",[e._v("Ensure that the "),n("code",[e._v("ApplicationEventsTestExecutionListener")]),e._v(" is registered. Note, however,\nthat "),n("code",[e._v("ApplicationEventsTestExecutionListener")]),e._v(" is registered by default and only needs\nto be manually registered if you have custom configuration via"),n("code",[e._v("@TestExecutionListeners")]),e._v(" that does not include the default listeners.")])]),e._v(" "),n("li",[n("p",[e._v("Annotate a field of type "),n("code",[e._v("ApplicationEvents")]),e._v(" with "),n("code",[e._v("@Autowired")]),e._v(" and use that instance of"),n("code",[e._v("ApplicationEvents")]),e._v(" in your test and lifecycle methods (such as "),n("code",[e._v("@BeforeEach")]),e._v(" and"),n("code",[e._v("@AfterEach")]),e._v(" methods in JUnit Jupiter).")]),e._v(" "),n("ul",[n("li",[e._v("When using the "),n("a",{attrs:{href:"#testcontext-junit-jupiter-extension"}},[e._v("SpringExtension for JUnit Jupiter")]),e._v(", you may declare a method\nparameter of type "),n("code",[e._v("ApplicationEvents")]),e._v(" in a test or lifecycle method as an alternative\nto an "),n("code",[e._v("@Autowired")]),e._v(" field in the test class.")])])])]),e._v(" "),n("p",[e._v("The following test class uses the "),n("code",[e._v("SpringExtension")]),e._v(" for JUnit Jupiter and"),n("a",{attrs:{href:"https://assertj.github.io/doc/",target:"_blank",rel:"noopener noreferrer"}},[e._v("AssertJ"),n("OutboundLink")],1),e._v(" to assert the types of application events\npublished while invoking a method in a Spring-managed component:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(/* ... */)\n@RecordApplicationEvents (1)\nclass OrderServiceTests {\n\n @Autowired\n OrderService orderService;\n\n @Autowired\n ApplicationEvents events; (2)\n\n @Test\n void submitOrder() {\n // Invoke method in OrderService that publishes an event\n orderService.submitOrder(new Order(/* ... */));\n // Verify that an OrderSubmitted event was published\n long numEvents = events.stream(OrderSubmitted.class).count(); (3)\n assertThat(numEvents).isEqualTo(1);\n }\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Annotate the test class with "),n("code",[e._v("@RecordApplicationEvents")]),e._v(".")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Inject the "),n("code",[e._v("ApplicationEvents")]),e._v(" instance for the current test.")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("3")])]),e._v(" "),n("td",[e._v("Use the "),n("code",[e._v("ApplicationEvents")]),e._v(" API to count how many "),n("code",[e._v("OrderSubmitted")]),e._v(" events were published.")])])])]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(/* ... */)\n@RecordApplicationEvents (1)\nclass OrderServiceTests {\n\n @Autowired\n lateinit var orderService: OrderService\n\n @Autowired\n lateinit var events: ApplicationEvents (2)\n\n @Test\n fun submitOrder() {\n // Invoke method in OrderService that publishes an event\n orderService.submitOrder(Order(/* ... */))\n // Verify that an OrderSubmitted event was published\n val numEvents = events.stream(OrderSubmitted::class).count() (3)\n assertThat(numEvents).isEqualTo(1)\n }\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Annotate the test class with "),n("code",[e._v("@RecordApplicationEvents")]),e._v(".")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Inject the "),n("code",[e._v("ApplicationEvents")]),e._v(" instance for the current test.")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("3")])]),e._v(" "),n("td",[e._v("Use the "),n("code",[e._v("ApplicationEvents")]),e._v(" API to count how many "),n("code",[e._v("OrderSubmitted")]),e._v(" events were published.")])])])]),e._v(" "),n("p",[e._v("See the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/event/ApplicationEvents.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("ApplicationEvents")]),e._v("javadoc"),n("OutboundLink")],1),e._v(" for further details regarding the "),n("code",[e._v("ApplicationEvents")]),e._v(" API.")]),e._v(" "),n("h4",{attrs:{id:"_3-5-5-test-execution-events"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-5-test-execution-events"}},[e._v("#")]),e._v(" 3.5.5. Test Execution Events")]),e._v(" "),n("p",[e._v("The "),n("code",[e._v("EventPublishingTestExecutionListener")]),e._v(" introduced in Spring Framework 5.2 offers an\nalternative approach to implementing a custom "),n("code",[e._v("TestExecutionListener")]),e._v(". Components in the\ntest’s "),n("code",[e._v("ApplicationContext")]),e._v(" can listen to the following events published by the"),n("code",[e._v("EventPublishingTestExecutionListener")]),e._v(", each of which corresponds to a method in the"),n("code",[e._v("TestExecutionListener")]),e._v(" API.")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("BeforeTestClassEvent")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("PrepareTestInstanceEvent")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("BeforeTestMethodEvent")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("BeforeTestExecutionEvent")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("AfterTestExecutionEvent")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("AfterTestMethodEvent")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("AfterTestClassEvent")])])])]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("These events are only published if the "),n("code",[e._v("ApplicationContext")]),e._v(" has already been loaded.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("These events may be consumed for various reasons, such as resetting mock beans or tracing\ntest execution. One advantage of consuming test execution events rather than implementing\na custom "),n("code",[e._v("TestExecutionListener")]),e._v(" is that test execution events may be consumed by any\nSpring bean registered in the test "),n("code",[e._v("ApplicationContext")]),e._v(", and such beans may benefit\ndirectly from dependency injection and other features of the "),n("code",[e._v("ApplicationContext")]),e._v(". In\ncontrast, a "),n("code",[e._v("TestExecutionListener")]),e._v(" is not a bean in the "),n("code",[e._v("ApplicationContext")]),e._v(".")]),e._v(" "),n("p",[e._v("In order to listen to test execution events, a Spring bean may choose to implement the"),n("code",[e._v("org.springframework.context.ApplicationListener")]),e._v(" interface. Alternatively, listener\nmethods can be annotated with "),n("code",[e._v("@EventListener")]),e._v(" and configured to listen to one of the\nparticular event types listed above (see"),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#context-functionality-events-annotation"}},[e._v("Annotation-based Event Listeners")]),e._v(").\nDue to the popularity of this approach, Spring provides the following dedicated"),n("code",[e._v("@EventListener")]),e._v(" annotations to simplify registration of test execution event listeners.\nThese annotations reside in the "),n("code",[e._v("org.springframework.test.context.event.annotation")]),e._v("package.")],1),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("@BeforeTestClass")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@PrepareTestInstance")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@BeforeTestMethod")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@BeforeTestExecution")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@AfterTestExecution")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@AfterTestMethod")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@AfterTestClass")])])])]),e._v(" "),n("h5",{attrs:{id:"exception-handling"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#exception-handling"}},[e._v("#")]),e._v(" Exception Handling")]),e._v(" "),n("p",[e._v("By default, if a test execution event listener throws an exception while consuming an\nevent, that exception will propagate to the underlying testing framework in use (such as\nJUnit or TestNG). For example, if the consumption of a "),n("code",[e._v("BeforeTestMethodEvent")]),e._v(" results in\nan exception, the corresponding test method will fail as a result of the exception. In\ncontrast, if an asynchronous test execution event listener throws an exception, the\nexception will not propagate to the underlying testing framework. For further details on\nasynchronous exception handling, consult the class-level javadoc for "),n("code",[e._v("@EventListener")]),e._v(".")]),e._v(" "),n("h5",{attrs:{id:"asynchronous-listeners"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#asynchronous-listeners"}},[e._v("#")]),e._v(" Asynchronous Listeners")]),e._v(" "),n("p",[e._v("If you want a particular test execution event listener to process events asynchronously,\nyou can use Spring’s "),n("RouterLink",{attrs:{to:"/en/spring-framework/integration.html#scheduling-annotation-support-async"}},[e._v("regular"),n("code",[e._v("@Async")]),e._v(" support")]),e._v(". For further details, consult the class-level javadoc for"),n("code",[e._v("@EventListener")]),e._v(".")],1),e._v(" "),n("h4",{attrs:{id:"_3-5-6-context-management"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-6-context-management"}},[e._v("#")]),e._v(" 3.5.6. Context Management")]),e._v(" "),n("p",[e._v("Each "),n("code",[e._v("TestContext")]),e._v(" provides context management and caching support for the test instance\nfor which it is responsible. Test instances do not automatically receive access to the\nconfigured "),n("code",[e._v("ApplicationContext")]),e._v(". However, if a test class implements the"),n("code",[e._v("ApplicationContextAware")]),e._v(" interface, a reference to the "),n("code",[e._v("ApplicationContext")]),e._v(" is supplied\nto the test instance. Note that "),n("code",[e._v("AbstractJUnit4SpringContextTests")]),e._v(" and"),n("code",[e._v("AbstractTestNGSpringContextTests")]),e._v(" implement "),n("code",[e._v("ApplicationContextAware")]),e._v(" and, therefore,\nprovide access to the "),n("code",[e._v("ApplicationContext")]),e._v(" automatically.")]),e._v(" "),n("p",[e._v("| |@Autowired ApplicationContext"),n("br"),n("br"),e._v("As an alternative to implementing the "),n("code",[e._v("ApplicationContextAware")]),e._v(" interface, you can inject"),n("br"),e._v("the application context for your test class through the "),n("code",[e._v("@Autowired")]),e._v(" annotation on either"),n("br"),e._v("a field or setter method, as the following example shows:"),n("br"),n("br"),e._v("Java"),n("br"),n("br"),n("code",[e._v("
@SpringJUnitConfig
class MyTest {

@Autowired (1)
ApplicationContext applicationContext;

// class body...
}
")]),n("br"),n("br"),e._v("|"),n("strong",[e._v("1")]),e._v("|Injecting the "),n("code",[e._v("ApplicationContext")]),e._v(".|"),n("br"),e._v("|-----|-----------------------------------|"),n("br"),n("br"),e._v("Kotlin"),n("br"),n("br"),n("code",[e._v("
@SpringJUnitConfig
class MyTest {

@Autowired (1)
lateinit var applicationContext: ApplicationContext

// class body...
}
")]),n("br"),n("br"),e._v("|"),n("strong",[e._v("1")]),e._v("|Injecting the "),n("code",[e._v("ApplicationContext")]),e._v(".|"),n("br"),e._v("|-----|-----------------------------------|"),n("br"),n("br"),e._v("Similarly, if your test is configured to load a "),n("code",[e._v("WebApplicationContext")]),e._v(", you can inject"),n("br"),e._v("the web application context into your test, as follows:"),n("br"),n("br"),e._v("Java"),n("br"),n("br"),n("code",[e._v("
@SpringJUnitWebConfig (1)
class MyWebAppTest {

@Autowired (2)
WebApplicationContext wac;

// class body...
}
")]),n("br"),n("br"),e._v("|"),n("strong",[e._v("1")]),e._v("|Configuring the "),n("code",[e._v("WebApplicationContext")]),e._v(".|"),n("br"),e._v("|-----|----------------------------------------|"),n("br"),e._v("|"),n("strong",[e._v("2")]),e._v("| Injecting the "),n("code",[e._v("WebApplicationContext")]),e._v(". |"),n("br"),n("br"),e._v("Kotlin"),n("br"),n("br"),n("code",[e._v("
@SpringJUnitWebConfig (1)
class MyWebAppTest {

@Autowired (2)
lateinit var wac: WebApplicationContext
// class body...
}
")]),n("br"),n("br"),e._v("|"),n("strong",[e._v("1")]),e._v("|Configuring the "),n("code",[e._v("WebApplicationContext")]),e._v(".|"),n("br"),e._v("|-----|----------------------------------------|"),n("br"),e._v("|"),n("strong",[e._v("2")]),e._v("| Injecting the "),n("code",[e._v("WebApplicationContext")]),e._v(". |"),n("br"),n("br"),e._v("Dependency injection by using "),n("code",[e._v("@Autowired")]),e._v(" is provided by the"),n("code",[e._v("DependencyInjectionTestExecutionListener")]),e._v(", which is configured by default"),n("br"),e._v("(see "),n("a",{attrs:{href:"#testcontext-fixture-di"}},[e._v("Dependency Injection of Test Fixtures")]),e._v(").|\n|-----|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n|"),n("strong",[e._v("1")]),e._v("| Injecting the "),n("code",[e._v("ApplicationContext")]),e._v(". |\n|"),n("strong",[e._v("1")]),e._v("| Injecting the "),n("code",[e._v("ApplicationContext")]),e._v(". |\n|"),n("strong",[e._v("1")]),e._v("| Configuring the "),n("code",[e._v("WebApplicationContext")]),e._v(". |\n|"),n("strong",[e._v("2")]),e._v("| Injecting the "),n("code",[e._v("WebApplicationContext")]),e._v(". |\n|"),n("strong",[e._v("1")]),e._v("| Configuring the "),n("code",[e._v("WebApplicationContext")]),e._v(". |\n|"),n("strong",[e._v("2")]),e._v("| Injecting the "),n("code",[e._v("WebApplicationContext")]),e._v(". |")]),e._v(" "),n("p",[e._v("Test classes that use the TestContext framework do not need to extend any particular\nclass or implement a specific interface to configure their application context. Instead,\nconfiguration is achieved by declaring the "),n("code",[e._v("@ContextConfiguration")]),e._v(" annotation at the\nclass level. If your test class does not explicitly declare application context resource\nlocations or component classes, the configured "),n("code",[e._v("ContextLoader")]),e._v(" determines how to load a\ncontext from a default location or default configuration classes. In addition to context\nresource locations and component classes, an application context can also be configured\nthrough application context initializers.")]),e._v(" "),n("p",[e._v("The following sections explain how to use Spring’s "),n("code",[e._v("@ContextConfiguration")]),e._v(" annotation to\nconfigure a test "),n("code",[e._v("ApplicationContext")]),e._v(" by using XML configuration files, Groovy scripts,\ncomponent classes (typically "),n("code",[e._v("@Configuration")]),e._v(" classes), or context initializers.\nAlternatively, you can implement and configure your own custom "),n("code",[e._v("SmartContextLoader")]),e._v(" for\nadvanced use cases.")]),e._v(" "),n("ul",[n("li",[n("p",[n("a",{attrs:{href:"#testcontext-ctx-management-xml"}},[e._v("Context Configuration with XML resources")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-ctx-management-groovy"}},[e._v("Context Configuration with Groovy Scripts")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-ctx-management-javaconfig"}},[e._v("Context Configuration with Component Classes")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-ctx-management-mixed-config"}},[e._v("Mixing XML, Groovy Scripts, and Component Classes")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-ctx-management-initializers"}},[e._v("Context Configuration with Context Initializers")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-ctx-management-inheritance"}},[e._v("Context Configuration Inheritance")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-ctx-management-env-profiles"}},[e._v("Context Configuration with Environment Profiles")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-ctx-management-property-sources"}},[e._v("Context Configuration with Test Property Sources")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-ctx-management-dynamic-property-sources"}},[e._v("Context Configuration with Dynamic Property Sources")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-ctx-management-web"}},[e._v("Loading a "),n("code",[e._v("WebApplicationContext")])])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-ctx-management-caching"}},[e._v("Context Caching")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#testcontext-ctx-management-ctx-hierarchies"}},[e._v("Context Hierarchies")])])])]),e._v(" "),n("h5",{attrs:{id:"context-configuration-with-xml-resources"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#context-configuration-with-xml-resources"}},[e._v("#")]),e._v(" Context Configuration with XML resources")]),e._v(" "),n("p",[e._v("To load an "),n("code",[e._v("ApplicationContext")]),e._v(" for your tests by using XML configuration files, annotate\nyour test class with "),n("code",[e._v("@ContextConfiguration")]),e._v(" and configure the "),n("code",[e._v("locations")]),e._v(" attribute with\nan array that contains the resource locations of XML configuration metadata. A plain or\nrelative path (for example, "),n("code",[e._v("context.xml")]),e._v(") is treated as a classpath resource that is\nrelative to the package in which the test class is defined. A path starting with a slash\nis treated as an absolute classpath location (for example, "),n("code",[e._v("/org/example/config.xml")]),e._v("). A\npath that represents a resource URL (i.e., a path prefixed with "),n("code",[e._v("classpath:")]),e._v(", "),n("code",[e._v("file:")]),e._v(","),n("code",[e._v("http:")]),e._v(", etc.) is used "),n("em",[e._v("as is")]),e._v(".")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n// ApplicationContext will be loaded from "/app-config.xml" and\n// "/test-config.xml" in the root of the classpath\n@ContextConfiguration(locations={"/app-config.xml", "/test-config.xml"}) (1)\nclass MyTest {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Setting the locations attribute to a list of XML files.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n// ApplicationContext will be loaded from "/app-config.xml" and\n// "/test-config.xml" in the root of the classpath\n@ContextConfiguration("/app-config.xml", "/test-config.xml") (1)\nclass MyTest {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Setting the locations attribute to a list of XML files.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[n("code",[e._v("@ContextConfiguration")]),e._v(" supports an alias for the "),n("code",[e._v("locations")]),e._v(" attribute through the\nstandard Java "),n("code",[e._v("value")]),e._v(" attribute. Thus, if you do not need to declare additional\nattributes in "),n("code",[e._v("@ContextConfiguration")]),e._v(", you can omit the declaration of the "),n("code",[e._v("locations")]),e._v("attribute name and declare the resource locations by using the shorthand format\ndemonstrated in the following example:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n@ContextConfiguration({"/app-config.xml", "/test-config.xml"}) (1)\nclass MyTest {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying XML files without using the "),n("code",[e._v("location")]),e._v(" attribute.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n@ContextConfiguration("/app-config.xml", "/test-config.xml") (1)\nclass MyTest {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying XML files without using the "),n("code",[e._v("location")]),e._v(" attribute.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("If you omit both the "),n("code",[e._v("locations")]),e._v(" and the "),n("code",[e._v("value")]),e._v(" attributes from the"),n("code",[e._v("@ContextConfiguration")]),e._v(" annotation, the TestContext framework tries to detect a default\nXML resource location. Specifically, "),n("code",[e._v("GenericXmlContextLoader")]),e._v(" and"),n("code",[e._v("GenericXmlWebContextLoader")]),e._v(" detect a default location based on the name of the test\nclass. If your class is named "),n("code",[e._v("com.example.MyTest")]),e._v(", "),n("code",[e._v("GenericXmlContextLoader")]),e._v(" loads your\napplication context from "),n("code",[e._v('"classpath:com/example/MyTest-context.xml"')]),e._v(". The following\nexample shows how to do so:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n// ApplicationContext will be loaded from\n// "classpath:com/example/MyTest-context.xml"\n@ContextConfiguration (1)\nclass MyTest {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Loading configuration from the default location.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n// ApplicationContext will be loaded from\n// "classpath:com/example/MyTest-context.xml"\n@ContextConfiguration (1)\nclass MyTest {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Loading configuration from the default location.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"context-configuration-with-groovy-scripts"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#context-configuration-with-groovy-scripts"}},[e._v("#")]),e._v(" Context Configuration with Groovy Scripts")]),e._v(" "),n("p",[e._v("To load an "),n("code",[e._v("ApplicationContext")]),e._v(" for your tests by using Groovy scripts that use the"),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#groovy-bean-definition-dsl"}},[e._v("Groovy Bean Definition DSL")]),e._v(", you can annotate\nyour test class with "),n("code",[e._v("@ContextConfiguration")]),e._v(" and configure the "),n("code",[e._v("locations")]),e._v(" or "),n("code",[e._v("value")]),e._v("attribute with an array that contains the resource locations of Groovy scripts. Resource\nlookup semantics for Groovy scripts are the same as those described for"),n("a",{attrs:{href:"#testcontext-ctx-management-xml"}},[e._v("XML configuration files")]),e._v(".")],1),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Enabling Groovy script support"),n("br"),n("br"),e._v("Support for using Groovy scripts to load an "),n("code",[e._v("ApplicationContext")]),e._v(" in the Spring"),n("br"),e._v("TestContext Framework is enabled automatically if Groovy is on the classpath.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("The following example shows how to specify Groovy configuration files:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n// ApplicationContext will be loaded from "/AppConfig.groovy" and\n// "/TestConfig.groovy" in the root of the classpath\n@ContextConfiguration({"/AppConfig.groovy", "/TestConfig.Groovy"}) (1)\nclass MyTest {\n // class body...\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n// ApplicationContext will be loaded from "/AppConfig.groovy" and\n// "/TestConfig.groovy" in the root of the classpath\n@ContextConfiguration("/AppConfig.groovy", "/TestConfig.Groovy") (1)\nclass MyTest {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying the location of Groovy configuration files.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("If you omit both the "),n("code",[e._v("locations")]),e._v(" and "),n("code",[e._v("value")]),e._v(" attributes from the "),n("code",[e._v("@ContextConfiguration")]),e._v("annotation, the TestContext framework tries to detect a default Groovy script.\nSpecifically, "),n("code",[e._v("GenericGroovyXmlContextLoader")]),e._v(" and "),n("code",[e._v("GenericGroovyXmlWebContextLoader")]),e._v("detect a default location based on the name of the test class. If your class is named"),n("code",[e._v("com.example.MyTest")]),e._v(", the Groovy context loader loads your application context from"),n("code",[e._v('"classpath:com/example/MyTestContext.groovy"')]),e._v(". The following example shows how to use\nthe default:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n// ApplicationContext will be loaded from\n// "classpath:com/example/MyTestContext.groovy"\n@ContextConfiguration (1)\nclass MyTest {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Loading configuration from the default location.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n// ApplicationContext will be loaded from\n// "classpath:com/example/MyTestContext.groovy"\n@ContextConfiguration (1)\nclass MyTest {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Loading configuration from the default location.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Declaring XML configuration and Groovy scripts simultaneously"),n("br"),n("br"),e._v("You can declare both XML configuration files and Groovy scripts simultaneously by using"),n("br"),e._v("the "),n("code",[e._v("locations")]),e._v(" or "),n("code",[e._v("value")]),e._v(" attribute of "),n("code",[e._v("@ContextConfiguration")]),e._v(". If the path to a"),n("br"),e._v("configured resource location ends with "),n("code",[e._v(".xml")]),e._v(", it is loaded by using an"),n("code",[e._v("XmlBeanDefinitionReader")]),e._v(". Otherwise, it is loaded by using a"),n("code",[e._v("GroovyBeanDefinitionReader")]),e._v("."),n("br"),n("br"),e._v("The following listing shows how to combine both in an integration test:"),n("br"),n("br"),e._v("Java"),n("br"),n("br"),n("code",[e._v('
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "/app-config.xml" and "/TestConfig.groovy"
@ContextConfiguration({ "/app-config.xml", "/TestConfig.groovy" })
class MyTest {
// class body...
}
')]),n("br"),n("br"),e._v("Kotlin"),n("br"),n("br"),n("code",[e._v('
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// "/app-config.xml" and "/TestConfig.groovy"
@ContextConfiguration("/app-config.xml", "/TestConfig.groovy")
class MyTest {
// class body...
}
')])])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"context-configuration-with-component-classes"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#context-configuration-with-component-classes"}},[e._v("#")]),e._v(" Context Configuration with Component Classes")]),e._v(" "),n("p",[e._v("To load an "),n("code",[e._v("ApplicationContext")]),e._v(" for your tests by using component classes (see"),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#beans-java"}},[e._v("Java-based container configuration")]),e._v("), you can annotate your test\nclass with "),n("code",[e._v("@ContextConfiguration")]),e._v(" and configure the "),n("code",[e._v("classes")]),e._v(" attribute with an array\nthat contains references to component classes. The following example shows how to do so:")],1),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ExtendWith(SpringExtension.class)\n// ApplicationContext will be loaded from AppConfig and TestConfig\n@ContextConfiguration(classes = {AppConfig.class, TestConfig.class}) (1)\nclass MyTest {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying component classes.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ExtendWith(SpringExtension::class)\n// ApplicationContext will be loaded from AppConfig and TestConfig\n@ContextConfiguration(classes = [AppConfig::class, TestConfig::class]) (1)\nclass MyTest {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying component classes.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Component Classes"),n("br"),n("br"),e._v("The term “component class” can refer to any of the following:"),n("br"),n("br"),e._v("* A class annotated with "),n("code",[e._v("@Configuration")]),e._v("."),n("br"),n("br"),e._v("* A component (that is, a class annotated with "),n("code",[e._v("@Component")]),e._v(", "),n("code",[e._v("@Service")]),e._v(", "),n("code",[e._v("@Repository")]),e._v(", or other stereotype annotations)."),n("br"),n("br"),e._v("* A JSR-330 compliant class that is annotated with "),n("code",[e._v("javax.inject")]),e._v(" annotations."),n("br"),n("br"),e._v("* Any class that contains "),n("code",[e._v("@Bean")]),e._v("-methods."),n("br"),n("br"),e._v("* Any other class that is intended to be registered as a Spring component (i.e., a Spring"),n("br"),e._v(" bean in the "),n("code",[e._v("ApplicationContext")]),e._v("), potentially taking advantage of automatic autowiring"),n("br"),e._v(" of a single constructor without the use of Spring annotations."),n("br"),n("br"),e._v("See the javadoc of"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/Configuration.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@Configuration")]),n("OutboundLink")],1),e._v(" and"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/Bean.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@Bean")]),n("OutboundLink")],1),e._v(" for further information"),n("br"),e._v("regarding the configuration and semantics of component classes, paying special attention"),n("br"),e._v("to the discussion of "),n("code",[e._v("@Bean")]),e._v(" Lite Mode.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("If you omit the "),n("code",[e._v("classes")]),e._v(" attribute from the "),n("code",[e._v("@ContextConfiguration")]),e._v(" annotation, the\nTestContext framework tries to detect the presence of default configuration classes.\nSpecifically, "),n("code",[e._v("AnnotationConfigContextLoader")]),e._v(" and "),n("code",[e._v("AnnotationConfigWebContextLoader")]),e._v("detect all "),n("code",[e._v("static")]),e._v(" nested classes of the test class that meet the requirements for\nconfiguration class implementations, as specified in the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/context/annotation/Configuration.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@Configuration")]),n("OutboundLink")],1),e._v(" javadoc.\nNote that the name of the configuration class is arbitrary. In addition, a test class can\ncontain more than one "),n("code",[e._v("static")]),e._v(" nested configuration class if desired. In the following\nexample, the "),n("code",[e._v("OrderServiceTest")]),e._v(" class declares a "),n("code",[e._v("static")]),e._v(" nested configuration class\nnamed "),n("code",[e._v("Config")]),e._v(" that is automatically used to load the "),n("code",[e._v("ApplicationContext")]),e._v(" for the test\nclass:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig (1)\n// ApplicationContext will be loaded from the\n// static nested Config class\nclass OrderServiceTest {\n\n @Configuration\n static class Config {\n\n // this bean will be injected into the OrderServiceTest class\n @Bean\n OrderService orderService() {\n OrderService orderService = new OrderServiceImpl();\n // set properties, etc.\n return orderService;\n }\n }\n\n @Autowired\n OrderService orderService;\n\n @Test\n void testOrderService() {\n // test the orderService\n }\n\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Loading configuration information from the nested "),n("code",[e._v("Config")]),e._v(" class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig (1)\n// ApplicationContext will be loaded from the nested Config class\nclass OrderServiceTest {\n\n @Autowired\n lateinit var orderService: OrderService\n\n @Configuration\n class Config {\n\n // this bean will be injected into the OrderServiceTest class\n @Bean\n fun orderService(): OrderService {\n // set properties, etc.\n return OrderServiceImpl()\n }\n }\n\n @Test\n fun testOrderService() {\n // test the orderService\n }\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Loading configuration information from the nested "),n("code",[e._v("Config")]),e._v(" class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"mixing-xml-groovy-scripts-and-component-classes"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#mixing-xml-groovy-scripts-and-component-classes"}},[e._v("#")]),e._v(" Mixing XML, Groovy Scripts, and Component Classes")]),e._v(" "),n("p",[e._v("It may sometimes be desirable to mix XML configuration files, Groovy scripts, and\ncomponent classes (typically "),n("code",[e._v("@Configuration")]),e._v(" classes) to configure an"),n("code",[e._v("ApplicationContext")]),e._v(" for your tests. For example, if you use XML configuration in\nproduction, you may decide that you want to use "),n("code",[e._v("@Configuration")]),e._v(" classes to configure\nspecific Spring-managed components for your tests, or vice versa.")]),e._v(" "),n("p",[e._v("Furthermore, some third-party frameworks (such as Spring Boot) provide first-class\nsupport for loading an "),n("code",[e._v("ApplicationContext")]),e._v(" from different types of resources\nsimultaneously (for example, XML configuration files, Groovy scripts, and"),n("code",[e._v("@Configuration")]),e._v(" classes). The Spring Framework, historically, has not supported this for\nstandard deployments. Consequently, most of the "),n("code",[e._v("SmartContextLoader")]),e._v(" implementations that\nthe Spring Framework delivers in the "),n("code",[e._v("spring-test")]),e._v(" module support only one resource type\nfor each test context. However, this does not mean that you cannot use both. One\nexception to the general rule is that the "),n("code",[e._v("GenericGroovyXmlContextLoader")]),e._v(" and"),n("code",[e._v("GenericGroovyXmlWebContextLoader")]),e._v(" support both XML configuration files and Groovy\nscripts simultaneously. Furthermore, third-party frameworks may choose to support the\ndeclaration of both "),n("code",[e._v("locations")]),e._v(" and "),n("code",[e._v("classes")]),e._v(" through "),n("code",[e._v("@ContextConfiguration")]),e._v(", and, with\nthe standard testing support in the TestContext framework, you have the following options.")]),e._v(" "),n("p",[e._v("If you want to use resource locations (for example, XML or Groovy) and "),n("code",[e._v("@Configuration")]),e._v("classes to configure your tests, you must pick one as the entry point, and that one must\ninclude or import the other. For example, in XML or Groovy scripts, you can include"),n("code",[e._v("@Configuration")]),e._v(" classes by using component scanning or defining them as normal Spring\nbeans, whereas, in a "),n("code",[e._v("@Configuration")]),e._v(" class, you can use "),n("code",[e._v("@ImportResource")]),e._v(" to import XML\nconfiguration files or Groovy scripts. Note that this behavior is semantically equivalent\nto how you configure your application in production: In production configuration, you\ndefine either a set of XML or Groovy resource locations or a set of "),n("code",[e._v("@Configuration")]),e._v("classes from which your production "),n("code",[e._v("ApplicationContext")]),e._v(" is loaded, but you still have the\nfreedom to include or import the other type of configuration.")]),e._v(" "),n("h5",{attrs:{id:"context-configuration-with-context-initializers"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#context-configuration-with-context-initializers"}},[e._v("#")]),e._v(" Context Configuration with Context Initializers")]),e._v(" "),n("p",[e._v("To configure an "),n("code",[e._v("ApplicationContext")]),e._v(" for your tests by using context initializers,\nannotate your test class with "),n("code",[e._v("@ContextConfiguration")]),e._v(" and configure the "),n("code",[e._v("initializers")]),e._v("attribute with an array that contains references to classes that implement"),n("code",[e._v("ApplicationContextInitializer")]),e._v(". The declared context initializers are then used to\ninitialize the "),n("code",[e._v("ConfigurableApplicationContext")]),e._v(" that is loaded for your tests. Note that\nthe concrete "),n("code",[e._v("ConfigurableApplicationContext")]),e._v(" type supported by each declared initializer\nmust be compatible with the type of "),n("code",[e._v("ApplicationContext")]),e._v(" created by the"),n("code",[e._v("SmartContextLoader")]),e._v(" in use (typically a "),n("code",[e._v("GenericApplicationContext")]),e._v("). Furthermore, the\norder in which the initializers are invoked depends on whether they implement Spring’s"),n("code",[e._v("Ordered")]),e._v(" interface or are annotated with Spring’s "),n("code",[e._v("@Order")]),e._v(" annotation or the standard"),n("code",[e._v("@Priority")]),e._v(" annotation. The following example shows how to use initializers:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ExtendWith(SpringExtension.class)\n// ApplicationContext will be loaded from TestConfig\n// and initialized by TestAppCtxInitializer\n@ContextConfiguration(\n classes = TestConfig.class,\n initializers = TestAppCtxInitializer.class) (1)\nclass MyTest {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying configuration by using a configuration class and an initializer.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ExtendWith(SpringExtension::class)\n// ApplicationContext will be loaded from TestConfig\n// and initialized by TestAppCtxInitializer\n@ContextConfiguration(\n classes = [TestConfig::class],\n initializers = [TestAppCtxInitializer::class]) (1)\nclass MyTest {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying configuration by using a configuration class and an initializer.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("You can also omit the declaration of XML configuration files, Groovy scripts, or\ncomponent classes in "),n("code",[e._v("@ContextConfiguration")]),e._v(" entirely and instead declare only"),n("code",[e._v("ApplicationContextInitializer")]),e._v(" classes, which are then responsible for registering beans\nin the context — for example, by programmatically loading bean definitions from XML\nfiles or configuration classes. The following example shows how to do so:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ExtendWith(SpringExtension.class)\n// ApplicationContext will be initialized by EntireAppInitializer\n// which presumably registers beans in the context\n@ContextConfiguration(initializers = EntireAppInitializer.class) (1)\nclass MyTest {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying configuration by using only an initializer.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ExtendWith(SpringExtension::class)\n// ApplicationContext will be initialized by EntireAppInitializer\n// which presumably registers beans in the context\n@ContextConfiguration(initializers = [EntireAppInitializer::class]) (1)\nclass MyTest {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying configuration by using only an initializer.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"context-configuration-inheritance"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#context-configuration-inheritance"}},[e._v("#")]),e._v(" Context Configuration Inheritance")]),e._v(" "),n("p",[n("code",[e._v("@ContextConfiguration")]),e._v(" supports boolean "),n("code",[e._v("inheritLocations")]),e._v(" and "),n("code",[e._v("inheritInitializers")]),e._v("attributes that denote whether resource locations or component classes and context\ninitializers declared by superclasses should be inherited. The default value for both\nflags is "),n("code",[e._v("true")]),e._v(". This means that a test class inherits the resource locations or\ncomponent classes as well as the context initializers declared by any superclasses.\nSpecifically, the resource locations or component classes for a test class are appended\nto the list of resource locations or annotated classes declared by superclasses.\nSimilarly, the initializers for a given test class are added to the set of initializers\ndefined by test superclasses. Thus, subclasses have the option of extending the resource\nlocations, component classes, or context initializers.")]),e._v(" "),n("p",[e._v("If the "),n("code",[e._v("inheritLocations")]),e._v(" or "),n("code",[e._v("inheritInitializers")]),e._v(" attribute in "),n("code",[e._v("@ContextConfiguration")]),e._v("is set to "),n("code",[e._v("false")]),e._v(", the resource locations or component classes and the context\ninitializers, respectively, for the test class shadow and effectively replace the\nconfiguration defined by superclasses.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("As of Spring Framework 5.3, test configuration may also be inherited from enclosing"),n("br"),e._v("classes. See "),n("a",{attrs:{href:"#testcontext-junit-jupiter-nested-test-configuration"}},[n("code",[e._v("@Nested")]),e._v(" test class configuration")]),e._v(" for details.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("In the next example, which uses XML resource locations, the "),n("code",[e._v("ApplicationContext")]),e._v(" for"),n("code",[e._v("ExtendedTest")]),e._v(" is loaded from "),n("code",[e._v("base-config.xml")]),e._v(" and "),n("code",[e._v("extended-config.xml")]),e._v(", in that order.\nBeans defined in "),n("code",[e._v("extended-config.xml")]),e._v(" can, therefore, override (that is, replace) those\ndefined in "),n("code",[e._v("base-config.xml")]),e._v(". The following example shows how one class can extend\nanother and use both its own configuration file and the superclass’s configuration file:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n// ApplicationContext will be loaded from "/base-config.xml"\n// in the root of the classpath\n@ContextConfiguration("/base-config.xml") (1)\nclass BaseTest {\n // class body...\n}\n\n// ApplicationContext will be loaded from "/base-config.xml" and\n// "/extended-config.xml" in the root of the classpath\n@ContextConfiguration("/extended-config.xml") (2)\nclass ExtendedTest extends BaseTest {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Configuration file defined in the superclass.")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Configuration file defined in the subclass.")])])])]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n// ApplicationContext will be loaded from "/base-config.xml"\n// in the root of the classpath\n@ContextConfiguration("/base-config.xml") (1)\nopen class BaseTest {\n // class body...\n}\n\n// ApplicationContext will be loaded from "/base-config.xml" and\n// "/extended-config.xml" in the root of the classpath\n@ContextConfiguration("/extended-config.xml") (2)\nclass ExtendedTest : BaseTest() {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Configuration file defined in the superclass.")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Configuration file defined in the subclass.")])])])]),e._v(" "),n("p",[e._v("Similarly, in the next example, which uses component classes, the "),n("code",[e._v("ApplicationContext")]),e._v("for "),n("code",[e._v("ExtendedTest")]),e._v(" is loaded from the "),n("code",[e._v("BaseConfig")]),e._v(" and "),n("code",[e._v("ExtendedConfig")]),e._v(" classes, in that\norder. Beans defined in "),n("code",[e._v("ExtendedConfig")]),e._v(" can, therefore, override (that is, replace)\nthose defined in "),n("code",[e._v("BaseConfig")]),e._v(". The following example shows how one class can extend\nanother and use both its own configuration class and the superclass’s configuration class:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// ApplicationContext will be loaded from BaseConfig\n@SpringJUnitConfig(BaseConfig.class) (1)\nclass BaseTest {\n // class body...\n}\n\n// ApplicationContext will be loaded from BaseConfig and ExtendedConfig\n@SpringJUnitConfig(ExtendedConfig.class) (2)\nclass ExtendedTest extends BaseTest {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Configuration class defined in the superclass.")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Configuration class defined in the subclass.")])])])]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// ApplicationContext will be loaded from BaseConfig\n@SpringJUnitConfig(BaseConfig::class) (1)\nopen class BaseTest {\n // class body...\n}\n\n// ApplicationContext will be loaded from BaseConfig and ExtendedConfig\n@SpringJUnitConfig(ExtendedConfig::class) (2)\nclass ExtendedTest : BaseTest() {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Configuration class defined in the superclass.")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Configuration class defined in the subclass.")])])])]),e._v(" "),n("p",[e._v("In the next example, which uses context initializers, the "),n("code",[e._v("ApplicationContext")]),e._v(" for"),n("code",[e._v("ExtendedTest")]),e._v(" is initialized by using "),n("code",[e._v("BaseInitializer")]),e._v(" and "),n("code",[e._v("ExtendedInitializer")]),e._v(". Note,\nhowever, that the order in which the initializers are invoked depends on whether they\nimplement Spring’s "),n("code",[e._v("Ordered")]),e._v(" interface or are annotated with Spring’s "),n("code",[e._v("@Order")]),e._v(" annotation\nor the standard "),n("code",[e._v("@Priority")]),e._v(" annotation. The following example shows how one class can\nextend another and use both its own initializer and the superclass’s initializer:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// ApplicationContext will be initialized by BaseInitializer\n@SpringJUnitConfig(initializers = BaseInitializer.class) (1)\nclass BaseTest {\n // class body...\n}\n\n// ApplicationContext will be initialized by BaseInitializer\n// and ExtendedInitializer\n@SpringJUnitConfig(initializers = ExtendedInitializer.class) (2)\nclass ExtendedTest extends BaseTest {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Initializer defined in the superclass.")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Initializer defined in the subclass.")])])])]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// ApplicationContext will be initialized by BaseInitializer\n@SpringJUnitConfig(initializers = [BaseInitializer::class]) (1)\nopen class BaseTest {\n // class body...\n}\n\n// ApplicationContext will be initialized by BaseInitializer\n// and ExtendedInitializer\n@SpringJUnitConfig(initializers = [ExtendedInitializer::class]) (2)\nclass ExtendedTest : BaseTest() {\n // class body...\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Initializer defined in the superclass.")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Initializer defined in the subclass.")])])])]),e._v(" "),n("h5",{attrs:{id:"context-configuration-with-environment-profiles"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#context-configuration-with-environment-profiles"}},[e._v("#")]),e._v(" Context Configuration with Environment Profiles")]),e._v(" "),n("p",[e._v('The Spring Framework has first-class support for the notion of environments and profiles\n(AKA "bean definition profiles"), and integration tests can be configured to activate\nparticular bean definition profiles for various testing scenarios. This is achieved by\nannotating a test class with the '),n("code",[e._v("@ActiveProfiles")]),e._v(" annotation and supplying a list of\nprofiles that should be activated when loading the "),n("code",[e._v("ApplicationContext")]),e._v(" for the test.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("You can use "),n("code",[e._v("@ActiveProfiles")]),e._v(" with any implementation of the "),n("code",[e._v("SmartContextLoader")]),e._v("SPI, but "),n("code",[e._v("@ActiveProfiles")]),e._v(" is not supported with implementations of the older"),n("code",[e._v("ContextLoader")]),e._v(" SPI.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Consider two examples with XML configuration and "),n("code",[e._v("@Configuration")]),e._v(" classes:")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('\x3c!-- app-config.xml --\x3e\n\n\n \n \n \n \n\n \n \n \n\n \n\n \n \n \n \n \n \n\n \n \n \n\n \n \n \n \n \n\n\n')])])]),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n// ApplicationContext will be loaded from "classpath:/app-config.xml"\n@ContextConfiguration("/app-config.xml")\n@ActiveProfiles("dev")\nclass TransferServiceTest {\n\n @Autowired\n TransferService transferService;\n\n @Test\n void testTransferService() {\n // test the transferService\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n// ApplicationContext will be loaded from "classpath:/app-config.xml"\n@ContextConfiguration("/app-config.xml")\n@ActiveProfiles("dev")\nclass TransferServiceTest {\n\n @Autowired\n lateinit var transferService: TransferService\n\n @Test\n fun testTransferService() {\n // test the transferService\n }\n}\n')])])]),n("p",[e._v("When "),n("code",[e._v("TransferServiceTest")]),e._v(" is run, its "),n("code",[e._v("ApplicationContext")]),e._v(" is loaded from the"),n("code",[e._v("app-config.xml")]),e._v(" configuration file in the root of the classpath. If you inspect"),n("code",[e._v("app-config.xml")]),e._v(", you can see that the "),n("code",[e._v("accountRepository")]),e._v(" bean has a dependency on a"),n("code",[e._v("dataSource")]),e._v(" bean. However, "),n("code",[e._v("dataSource")]),e._v(" is not defined as a top-level bean. Instead,"),n("code",[e._v("dataSource")]),e._v(" is defined three times: in the "),n("code",[e._v("production")]),e._v(" profile, in the "),n("code",[e._v("dev")]),e._v(" profile,\nand in the "),n("code",[e._v("default")]),e._v(" profile.")]),e._v(" "),n("p",[e._v("By annotating "),n("code",[e._v("TransferServiceTest")]),e._v(" with "),n("code",[e._v('@ActiveProfiles("dev")')]),e._v(", we instruct the Spring\nTestContext Framework to load the "),n("code",[e._v("ApplicationContext")]),e._v(" with the active profiles set to"),n("code",[e._v('{"dev"}')]),e._v(". As a result, an embedded database is created and populated with test data, and\nthe "),n("code",[e._v("accountRepository")]),e._v(" bean is wired with a reference to the development "),n("code",[e._v("DataSource")]),e._v(".\nThat is likely what we want in an integration test.")]),e._v(" "),n("p",[e._v("It is sometimes useful to assign beans to a "),n("code",[e._v("default")]),e._v(" profile. Beans within the default\nprofile are included only when no other profile is specifically activated. You can use\nthis to define “fallback” beans to be used in the application’s default state. For\nexample, you may explicitly provide a data source for "),n("code",[e._v("dev")]),e._v(" and "),n("code",[e._v("production")]),e._v(" profiles,\nbut define an in-memory data source as a default when neither of these is active.")]),e._v(" "),n("p",[e._v("The following code listings demonstrate how to implement the same configuration and\nintegration test with "),n("code",[e._v("@Configuration")]),e._v(" classes instead of XML:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Configuration\n@Profile("dev")\npublic class StandaloneDataConfig {\n\n @Bean\n public DataSource dataSource() {\n return new EmbeddedDatabaseBuilder()\n .setType(EmbeddedDatabaseType.HSQL)\n .addScript("classpath:com/bank/config/sql/schema.sql")\n .addScript("classpath:com/bank/config/sql/test-data.sql")\n .build();\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Configuration\n@Profile("dev")\nclass StandaloneDataConfig {\n\n @Bean\n fun dataSource(): DataSource {\n return EmbeddedDatabaseBuilder()\n .setType(EmbeddedDatabaseType.HSQL)\n .addScript("classpath:com/bank/config/sql/schema.sql")\n .addScript("classpath:com/bank/config/sql/test-data.sql")\n .build()\n }\n}\n')])])]),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Configuration\n@Profile("production")\npublic class JndiDataConfig {\n\n @Bean(destroyMethod="")\n public DataSource dataSource() throws Exception {\n Context ctx = new InitialContext();\n return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Configuration\n@Profile("production")\nclass JndiDataConfig {\n\n @Bean(destroyMethod = "")\n fun dataSource(): DataSource {\n val ctx = InitialContext()\n return ctx.lookup("java:comp/env/jdbc/datasource") as DataSource\n }\n}\n')])])]),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Configuration\n@Profile("default")\npublic class DefaultDataConfig {\n\n @Bean\n public DataSource dataSource() {\n return new EmbeddedDatabaseBuilder()\n .setType(EmbeddedDatabaseType.HSQL)\n .addScript("classpath:com/bank/config/sql/schema.sql")\n .build();\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Configuration\n@Profile("default")\nclass DefaultDataConfig {\n\n @Bean\n fun dataSource(): DataSource {\n return EmbeddedDatabaseBuilder()\n .setType(EmbeddedDatabaseType.HSQL)\n .addScript("classpath:com/bank/config/sql/schema.sql")\n .build()\n }\n}\n')])])]),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Configuration\npublic class TransferServiceConfig {\n\n @Autowired DataSource dataSource;\n\n @Bean\n public TransferService transferService() {\n return new DefaultTransferService(accountRepository(), feePolicy());\n }\n\n @Bean\n public AccountRepository accountRepository() {\n return new JdbcAccountRepository(dataSource);\n }\n\n @Bean\n public FeePolicy feePolicy() {\n return new ZeroFeePolicy();\n }\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@Configuration\nclass TransferServiceConfig {\n\n @Autowired\n lateinit var dataSource: DataSource\n\n @Bean\n fun transferService(): TransferService {\n return DefaultTransferService(accountRepository(), feePolicy())\n }\n\n @Bean\n fun accountRepository(): AccountRepository {\n return JdbcAccountRepository(dataSource)\n }\n\n @Bean\n fun feePolicy(): FeePolicy {\n return ZeroFeePolicy()\n }\n}\n")])])]),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig({\n TransferServiceConfig.class,\n StandaloneDataConfig.class,\n JndiDataConfig.class,\n DefaultDataConfig.class})\n@ActiveProfiles("dev")\nclass TransferServiceTest {\n\n @Autowired\n TransferService transferService;\n\n @Test\n void testTransferService() {\n // test the transferService\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(\n TransferServiceConfig::class,\n StandaloneDataConfig::class,\n JndiDataConfig::class,\n DefaultDataConfig::class)\n@ActiveProfiles("dev")\nclass TransferServiceTest {\n\n @Autowired\n lateinit var transferService: TransferService\n\n @Test\n fun testTransferService() {\n // test the transferService\n }\n}\n')])])]),n("p",[e._v("In this variation, we have split the XML configuration into four independent"),n("code",[e._v("@Configuration")]),e._v(" classes:")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("TransferServiceConfig")]),e._v(": Acquires a "),n("code",[e._v("dataSource")]),e._v(" through dependency injection by using"),n("code",[e._v("@Autowired")]),e._v(".")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("StandaloneDataConfig")]),e._v(": Defines a "),n("code",[e._v("dataSource")]),e._v(" for an embedded database suitable for\ndeveloper tests.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("JndiDataConfig")]),e._v(": Defines a "),n("code",[e._v("dataSource")]),e._v(" that is retrieved from JNDI in a production\nenvironment.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("DefaultDataConfig")]),e._v(": Defines a "),n("code",[e._v("dataSource")]),e._v(" for a default embedded database, in case no\nprofile is active.")])])]),e._v(" "),n("p",[e._v("As with the XML-based configuration example, we still annotate "),n("code",[e._v("TransferServiceTest")]),e._v(" with"),n("code",[e._v('@ActiveProfiles("dev")')]),e._v(", but this time we specify all four configuration classes by\nusing the "),n("code",[e._v("@ContextConfiguration")]),e._v(" annotation. The body of the test class itself remains\ncompletely unchanged.")]),e._v(" "),n("p",[e._v("It is often the case that a single set of profiles is used across multiple test classes\nwithin a given project. Thus, to avoid duplicate declarations of the "),n("code",[e._v("@ActiveProfiles")]),e._v("annotation, you can declare "),n("code",[e._v("@ActiveProfiles")]),e._v(" once on a base class, and subclasses\nautomatically inherit the "),n("code",[e._v("@ActiveProfiles")]),e._v(" configuration from the base class. In the\nfollowing example, the declaration of "),n("code",[e._v("@ActiveProfiles")]),e._v(" (as well as other annotations)\nhas been moved to an abstract superclass, "),n("code",[e._v("AbstractIntegrationTest")]),e._v(":")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("As of Spring Framework 5.3, test configuration may also be inherited from enclosing"),n("br"),e._v("classes. See "),n("a",{attrs:{href:"#testcontext-junit-jupiter-nested-test-configuration"}},[n("code",[e._v("@Nested")]),e._v(" test class configuration")]),e._v(" for details.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig({\n TransferServiceConfig.class,\n StandaloneDataConfig.class,\n JndiDataConfig.class,\n DefaultDataConfig.class})\n@ActiveProfiles("dev")\nabstract class AbstractIntegrationTest {\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(\n TransferServiceConfig::class,\n StandaloneDataConfig::class,\n JndiDataConfig::class,\n DefaultDataConfig::class)\n@ActiveProfiles("dev")\nabstract class AbstractIntegrationTest {\n}\n')])])]),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// "dev" profile inherited from superclass\nclass TransferServiceTest extends AbstractIntegrationTest {\n\n @Autowired\n TransferService transferService;\n\n @Test\n void testTransferService() {\n // test the transferService\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// "dev" profile inherited from superclass\nclass TransferServiceTest : AbstractIntegrationTest() {\n\n @Autowired\n lateinit var transferService: TransferService\n\n @Test\n fun testTransferService() {\n // test the transferService\n }\n}\n')])])]),n("p",[n("code",[e._v("@ActiveProfiles")]),e._v(" also supports an "),n("code",[e._v("inheritProfiles")]),e._v(" attribute that can be used to\ndisable the inheritance of active profiles, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// "dev" profile overridden with "production"\n@ActiveProfiles(profiles = "production", inheritProfiles = false)\nclass ProductionTransferServiceTest extends AbstractIntegrationTest {\n // test body\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// "dev" profile overridden with "production"\n@ActiveProfiles("production", inheritProfiles = false)\nclass ProductionTransferServiceTest : AbstractIntegrationTest() {\n // test body\n}\n')])])]),n("p",[e._v("Furthermore, it is sometimes necessary to resolve active profiles for tests\nprogrammatically instead of declaratively — for example, based on:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("The current operating system.")])]),e._v(" "),n("li",[n("p",[e._v("Whether tests are being run on a continuous integration build server.")])]),e._v(" "),n("li",[n("p",[e._v("The presence of certain environment variables.")])]),e._v(" "),n("li",[n("p",[e._v("The presence of custom class-level annotations.")])]),e._v(" "),n("li",[n("p",[e._v("Other concerns.")])])]),e._v(" "),n("p",[e._v("To resolve active bean definition profiles programmatically, you can implement\na custom "),n("code",[e._v("ActiveProfilesResolver")]),e._v(" and register it by using the "),n("code",[e._v("resolver")]),e._v("attribute of "),n("code",[e._v("@ActiveProfiles")]),e._v(". For further information, see the corresponding"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/ActiveProfilesResolver.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("javadoc"),n("OutboundLink")],1),e._v(".\nThe following example demonstrates how to implement and register a custom"),n("code",[e._v("OperatingSystemActiveProfilesResolver")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// "dev" profile overridden programmatically via a custom resolver\n@ActiveProfiles(\n resolver = OperatingSystemActiveProfilesResolver.class,\n inheritProfiles = false)\nclass TransferServiceTest extends AbstractIntegrationTest {\n // test body\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// "dev" profile overridden programmatically via a custom resolver\n@ActiveProfiles(\n resolver = OperatingSystemActiveProfilesResolver::class,\n inheritProfiles = false)\nclass TransferServiceTest : AbstractIntegrationTest() {\n // test body\n}\n')])])]),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("public class OperatingSystemActiveProfilesResolver implements ActiveProfilesResolver {\n\n @Override\n public String[] resolve(Class testClass) {\n String profile = ...;\n // determine the value of profile based on the operating system\n return new String[] {profile};\n }\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("class OperatingSystemActiveProfilesResolver : ActiveProfilesResolver {\n\n override fun resolve(testClass: Class<*>): Array {\n val profile: String = ...\n // determine the value of profile based on the operating system\n return arrayOf(profile)\n }\n}\n")])])]),n("h5",{attrs:{id:"context-configuration-with-test-property-sources"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#context-configuration-with-test-property-sources"}},[e._v("#")]),e._v(" Context Configuration with Test Property Sources")]),e._v(" "),n("p",[e._v("The Spring Framework has first-class support for the notion of an environment with a\nhierarchy of property sources, and you can configure integration tests with test-specific\nproperty sources. In contrast to the "),n("code",[e._v("@PropertySource")]),e._v(" annotation used on"),n("code",[e._v("@Configuration")]),e._v(" classes, you can declare the "),n("code",[e._v("@TestPropertySource")]),e._v(" annotation on a test\nclass to declare resource locations for test properties files or inlined properties.\nThese test property sources are added to the set of "),n("code",[e._v("PropertySources")]),e._v(" in the"),n("code",[e._v("Environment")]),e._v(" for the "),n("code",[e._v("ApplicationContext")]),e._v(" loaded for the annotated integration test.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("You can use "),n("code",[e._v("@TestPropertySource")]),e._v(" with any implementation of the "),n("code",[e._v("SmartContextLoader")]),e._v("SPI, but "),n("code",[e._v("@TestPropertySource")]),e._v(" is not supported with implementations of the older"),n("code",[e._v("ContextLoader")]),e._v(" SPI."),n("br"),n("br"),e._v("Implementations of "),n("code",[e._v("SmartContextLoader")]),e._v(" gain access to merged test property source values"),n("br"),e._v("through the "),n("code",[e._v("getPropertySourceLocations()")]),e._v(" and "),n("code",[e._v("getPropertySourceProperties()")]),e._v(" methods in"),n("code",[e._v("MergedContextConfiguration")]),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h6",{attrs:{id:"declaring-test-property-sources"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#declaring-test-property-sources"}},[e._v("#")]),e._v(" Declaring Test Property Sources")]),e._v(" "),n("p",[e._v("You can configure test properties files by using the "),n("code",[e._v("locations")]),e._v(" or "),n("code",[e._v("value")]),e._v(" attribute of"),n("code",[e._v("@TestPropertySource")]),e._v(".")]),e._v(" "),n("p",[e._v("Both traditional and XML-based properties file formats are supported — for example,"),n("code",[e._v('"classpath:/com/example/test.properties"')]),e._v(" or "),n("code",[e._v('"file:///path/to/file.xml"')]),e._v(".")]),e._v(" "),n("p",[e._v("Each path is interpreted as a Spring "),n("code",[e._v("Resource")]),e._v(". A plain path (for example,"),n("code",[e._v('"test.properties"')]),e._v(") is treated as a classpath resource that is relative to the package\nin which the test class is defined. A path starting with a slash is treated as an\nabsolute classpath resource (for example: "),n("code",[e._v('"/org/example/test.xml"')]),e._v("). A path that\nreferences a URL (for example, a path prefixed with "),n("code",[e._v("classpath:")]),e._v(", "),n("code",[e._v("file:")]),e._v(", or "),n("code",[e._v("http:")]),e._v(") is\nloaded by using the specified resource protocol. Resource location wildcards (such as"),n("code",[e._v("***/**.properties")]),e._v(") are not permitted: Each location must evaluate to exactly one"),n("code",[e._v(".properties")]),e._v(" or "),n("code",[e._v(".xml")]),e._v(" resource.")]),e._v(" "),n("p",[e._v("The following example uses a test properties file:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@TestPropertySource("/test.properties") (1)\nclass MyIntegrationTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying a properties file with an absolute path.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@TestPropertySource("/test.properties") (1)\nclass MyIntegrationTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specifying a properties file with an absolute path.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("You can configure inlined properties in the form of key-value pairs by using the"),n("code",[e._v("properties")]),e._v(" attribute of "),n("code",[e._v("@TestPropertySource")]),e._v(", as shown in the next example. All\nkey-value pairs are added to the enclosing "),n("code",[e._v("Environment")]),e._v(" as a single test"),n("code",[e._v("PropertySource")]),e._v(" with the highest precedence.")]),e._v(" "),n("p",[e._v("The supported syntax for key-value pairs is the same as the syntax defined for entries in\na Java properties file:")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("key=value")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("key:value")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("key value")])])])]),e._v(" "),n("p",[e._v("The following example sets two inlined properties:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@TestPropertySource(properties = {"timezone = GMT", "port: 4242"}) (1)\nclass MyIntegrationTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Setting two properties by using two variations of the key-value syntax.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@TestPropertySource(properties = ["timezone = GMT", "port: 4242"]) (1)\nclass MyIntegrationTests {\n // class body...\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Setting two properties by using two variations of the key-value syntax.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("As of Spring Framework 5.2, "),n("code",[e._v("@TestPropertySource")]),e._v(" can be used as "),n("em",[e._v("repeatable annotation")]),e._v("."),n("br"),e._v("That means that you can have multiple declarations of "),n("code",[e._v("@TestPropertySource")]),e._v(" on a single"),n("br"),e._v("test class, with the "),n("code",[e._v("locations")]),e._v(" and "),n("code",[e._v("properties")]),e._v(" from later "),n("code",[e._v("@TestPropertySource")]),e._v("annotations overriding those from previous "),n("code",[e._v("@TestPropertySource")]),e._v(" annotations."),n("br"),n("br"),e._v("In addition, you may declare multiple composed annotations on a test class that are each"),n("br"),e._v("meta-annotated with "),n("code",[e._v("@TestPropertySource")]),e._v(", and all of those "),n("code",[e._v("@TestPropertySource")]),e._v("declarations will contribute to your test property sources."),n("br"),n("br"),e._v("Directly present "),n("code",[e._v("@TestPropertySource")]),e._v(" annotations always take precedence over"),n("br"),e._v("meta-present "),n("code",[e._v("@TestPropertySource")]),e._v(" annotations. In other words, "),n("code",[e._v("locations")]),e._v(" and"),n("code",[e._v("properties")]),e._v(" from a directly present "),n("code",[e._v("@TestPropertySource")]),e._v(" annotation will override the"),n("code",[e._v("locations")]),e._v(" and "),n("code",[e._v("properties")]),e._v(" from a "),n("code",[e._v("@TestPropertySource")]),e._v(" annotation used as a"),n("br"),e._v("meta-annotation.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h6",{attrs:{id:"default-properties-file-detection"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#default-properties-file-detection"}},[e._v("#")]),e._v(" Default Properties File Detection")]),e._v(" "),n("p",[e._v("If "),n("code",[e._v("@TestPropertySource")]),e._v(" is declared as an empty annotation (that is, without explicit\nvalues for the "),n("code",[e._v("locations")]),e._v(" or "),n("code",[e._v("properties")]),e._v(" attributes), an attempt is made to detect a\ndefault properties file relative to the class that declared the annotation. For example,\nif the annotated test class is "),n("code",[e._v("com.example.MyTest")]),e._v(", the corresponding default properties\nfile is "),n("code",[e._v("classpath:com/example/MyTest.properties")]),e._v(". If the default cannot be detected, an"),n("code",[e._v("IllegalStateException")]),e._v(" is thrown.")]),e._v(" "),n("h6",{attrs:{id:"precedence"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#precedence"}},[e._v("#")]),e._v(" Precedence")]),e._v(" "),n("p",[e._v("Test properties have higher precedence than those defined in the operating system’s\nenvironment, Java system properties, or property sources added by the application\ndeclaratively by using "),n("code",[e._v("@PropertySource")]),e._v(" or programmatically. Thus, test properties can\nbe used to selectively override properties loaded from system and application property\nsources. Furthermore, inlined properties have higher precedence than properties loaded\nfrom resource locations. Note, however, that properties registered via"),n("a",{attrs:{href:"#testcontext-ctx-management-dynamic-property-sources"}},[n("code",[e._v("@DynamicPropertySource")])]),e._v(" have\nhigher precedence than those loaded via "),n("code",[e._v("@TestPropertySource")]),e._v(".")]),e._v(" "),n("p",[e._v("In the next example, the "),n("code",[e._v("timezone")]),e._v(" and "),n("code",[e._v("port")]),e._v(" properties and any properties defined in"),n("code",[e._v('"/test.properties"')]),e._v(" override any properties of the same name that are defined in system\nand application property sources. Furthermore, if the "),n("code",[e._v('"/test.properties"')]),e._v(" file defines\nentries for the "),n("code",[e._v("timezone")]),e._v(" and "),n("code",[e._v("port")]),e._v(" properties those are overridden by the inlined\nproperties declared by using the "),n("code",[e._v("properties")]),e._v(" attribute. The following example shows how\nto specify properties both in a file and inline:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@TestPropertySource(\n locations = "/test.properties",\n properties = {"timezone = GMT", "port: 4242"}\n)\nclass MyIntegrationTests {\n // class body...\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration\n@TestPropertySource("/test.properties",\n properties = ["timezone = GMT", "port: 4242"]\n)\nclass MyIntegrationTests {\n // class body...\n}\n')])])]),n("h6",{attrs:{id:"inheriting-and-overriding-test-property-sources"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#inheriting-and-overriding-test-property-sources"}},[e._v("#")]),e._v(" Inheriting and Overriding Test Property Sources")]),e._v(" "),n("p",[n("code",[e._v("@TestPropertySource")]),e._v(" supports boolean "),n("code",[e._v("inheritLocations")]),e._v(" and "),n("code",[e._v("inheritProperties")]),e._v("attributes that denote whether resource locations for properties files and inlined\nproperties declared by superclasses should be inherited. The default value for both flags\nis "),n("code",[e._v("true")]),e._v(". This means that a test class inherits the locations and inlined properties\ndeclared by any superclasses. Specifically, the locations and inlined properties for a\ntest class are appended to the locations and inlined properties declared by superclasses.\nThus, subclasses have the option of extending the locations and inlined properties. Note\nthat properties that appear later shadow (that is, override) properties of the same name\nthat appear earlier. In addition, the aforementioned precedence rules apply for inherited\ntest property sources as well.")]),e._v(" "),n("p",[e._v("If the "),n("code",[e._v("inheritLocations")]),e._v(" or "),n("code",[e._v("inheritProperties")]),e._v(" attribute in "),n("code",[e._v("@TestPropertySource")]),e._v(" is\nset to "),n("code",[e._v("false")]),e._v(", the locations or inlined properties, respectively, for the test class\nshadow and effectively replace the configuration defined by superclasses.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("As of Spring Framework 5.3, test configuration may also be inherited from enclosing"),n("br"),e._v("classes. See "),n("a",{attrs:{href:"#testcontext-junit-jupiter-nested-test-configuration"}},[n("code",[e._v("@Nested")]),e._v(" test class configuration")]),e._v(" for details.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("In the next example, the "),n("code",[e._v("ApplicationContext")]),e._v(" for "),n("code",[e._v("BaseTest")]),e._v(" is loaded by using only the"),n("code",[e._v("base.properties")]),e._v(" file as a test property source. In contrast, the "),n("code",[e._v("ApplicationContext")]),e._v("for "),n("code",[e._v("ExtendedTest")]),e._v(" is loaded by using the "),n("code",[e._v("base.properties")]),e._v(" and "),n("code",[e._v("extended.properties")]),e._v("files as test property source locations. The following example shows how to define\nproperties in both a subclass and its superclass by using "),n("code",[e._v("properties")]),e._v(" files:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@TestPropertySource("base.properties")\n@ContextConfiguration\nclass BaseTest {\n // ...\n}\n\n@TestPropertySource("extended.properties")\n@ContextConfiguration\nclass ExtendedTest extends BaseTest {\n // ...\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@TestPropertySource("base.properties")\n@ContextConfiguration\nopen class BaseTest {\n // ...\n}\n\n@TestPropertySource("extended.properties")\n@ContextConfiguration\nclass ExtendedTest : BaseTest() {\n // ...\n}\n')])])]),n("p",[e._v("In the next example, the "),n("code",[e._v("ApplicationContext")]),e._v(" for "),n("code",[e._v("BaseTest")]),e._v(" is loaded by using only the\ninlined "),n("code",[e._v("key1")]),e._v(" property. In contrast, the "),n("code",[e._v("ApplicationContext")]),e._v(" for "),n("code",[e._v("ExtendedTest")]),e._v(" is\nloaded by using the inlined "),n("code",[e._v("key1")]),e._v(" and "),n("code",[e._v("key2")]),e._v(" properties. The following example shows how\nto define properties in both a subclass and its superclass by using inline properties:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@TestPropertySource(properties = "key1 = value1")\n@ContextConfiguration\nclass BaseTest {\n // ...\n}\n\n@TestPropertySource(properties = "key2 = value2")\n@ContextConfiguration\nclass ExtendedTest extends BaseTest {\n // ...\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@TestPropertySource(properties = ["key1 = value1"])\n@ContextConfiguration\nopen class BaseTest {\n // ...\n}\n\n@TestPropertySource(properties = ["key2 = value2"])\n@ContextConfiguration\nclass ExtendedTest : BaseTest() {\n // ...\n}\n')])])]),n("h5",{attrs:{id:"context-configuration-with-dynamic-property-sources"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#context-configuration-with-dynamic-property-sources"}},[e._v("#")]),e._v(" Context Configuration with Dynamic Property Sources")]),e._v(" "),n("p",[e._v("As of Spring Framework 5.2.5, the TestContext framework provides support for "),n("em",[e._v("dynamic")]),e._v("properties via the "),n("code",[e._v("@DynamicPropertySource")]),e._v(" annotation. This annotation can be used in\nintegration tests that need to add properties with dynamic values to the set of"),n("code",[e._v("PropertySources")]),e._v(" in the "),n("code",[e._v("Environment")]),e._v(" for the "),n("code",[e._v("ApplicationContext")]),e._v(" loaded for the\nintegration test.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("The "),n("code",[e._v("@DynamicPropertySource")]),e._v(" annotation and its supporting infrastructure were"),n("br"),e._v("originally designed to allow properties from"),n("a",{attrs:{href:"https://www.testcontainers.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Testcontainers"),n("OutboundLink")],1),e._v(" based tests to be exposed easily to"),n("br"),e._v("Spring integration tests. However, this feature may also be used with any form of"),n("br"),e._v("external resource whose lifecycle is maintained outside the test’s "),n("code",[e._v("ApplicationContext")]),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("In contrast to the "),n("a",{attrs:{href:"#testcontext-ctx-management-property-sources"}},[n("code",[e._v("@TestPropertySource")])]),e._v("annotation that is applied at the class level, "),n("code",[e._v("@DynamicPropertySource")]),e._v(" must be applied\nto a "),n("code",[e._v("static")]),e._v(" method that accepts a single "),n("code",[e._v("DynamicPropertyRegistry")]),e._v(" argument which is\nused to add "),n("em",[e._v("name-value")]),e._v(" pairs to the "),n("code",[e._v("Environment")]),e._v(". Values are dynamic and provided via\na "),n("code",[e._v("Supplier")]),e._v(" which is only invoked when the property is resolved. Typically, method\nreferences are used to supply values, as can be seen in the following example which uses\nthe Testcontainers project to manage a Redis container outside of the Spring"),n("code",[e._v("ApplicationContext")]),e._v(". The IP address and port of the managed Redis container are made\navailable to components within the test’s "),n("code",[e._v("ApplicationContext")]),e._v(" via the "),n("code",[e._v("redis.host")]),e._v(" and"),n("code",[e._v("redis.port")]),e._v(" properties. These properties can be accessed via Spring’s "),n("code",[e._v("Environment")]),e._v("abstraction or injected directly into Spring-managed components – for example, via"),n("code",[e._v('@Value("${redis.host}")')]),e._v(" and "),n("code",[e._v('@Value("${redis.port}")')]),e._v(", respectively.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("If you use "),n("code",[e._v("@DynamicPropertySource")]),e._v(" in a base class and discover that tests in subclasses"),n("br"),e._v("fail because the dynamic properties change between subclasses, you may need to annotate"),n("br"),e._v("your base class with "),n("a",{attrs:{href:"#spring-testing-annotation-dirtiescontext"}},[n("code",[e._v("@DirtiesContext")])]),e._v(" to"),n("br"),e._v("ensure that each subclass gets its own "),n("code",[e._v("ApplicationContext")]),e._v(" with the correct dynamic"),n("br"),e._v("properties.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(/* ... */)\n@Testcontainers\nclass ExampleIntegrationTests {\n\n @Container\n static RedisContainer redis = new RedisContainer();\n\n @DynamicPropertySource\n static void redisProperties(DynamicPropertyRegistry registry) {\n registry.add("redis.host", redis::getContainerIpAddress);\n registry.add("redis.port", redis::getMappedPort);\n }\n\n // tests ...\n\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(/* ... */)\n@Testcontainers\nclass ExampleIntegrationTests {\n\n companion object {\n\n @Container\n @JvmStatic\n val redis: RedisContainer = RedisContainer()\n\n @DynamicPropertySource\n @JvmStatic\n fun redisProperties(registry: DynamicPropertyRegistry) {\n registry.add("redis.host", redis::getContainerIpAddress)\n registry.add("redis.port", redis::getMappedPort)\n }\n }\n\n // tests ...\n\n}\n')])])]),n("h6",{attrs:{id:"precedence-2"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#precedence-2"}},[e._v("#")]),e._v(" Precedence")]),e._v(" "),n("p",[e._v("Dynamic properties have higher precedence than those loaded from "),n("code",[e._v("@TestPropertySource")]),e._v(",\nthe operating system’s environment, Java system properties, or property sources added by\nthe application declaratively by using "),n("code",[e._v("@PropertySource")]),e._v(" or programmatically. Thus,\ndynamic properties can be used to selectively override properties loaded via"),n("code",[e._v("@TestPropertySource")]),e._v(", system property sources, and application property sources.")]),e._v(" "),n("h5",{attrs:{id:"loading-a-webapplicationcontext"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#loading-a-webapplicationcontext"}},[e._v("#")]),e._v(" Loading a "),n("code",[e._v("WebApplicationContext")])]),e._v(" "),n("p",[e._v("To instruct the TestContext framework to load a "),n("code",[e._v("WebApplicationContext")]),e._v(" instead of a\nstandard "),n("code",[e._v("ApplicationContext")]),e._v(", you can annotate the respective test class with"),n("code",[e._v("@WebAppConfiguration")]),e._v(".")]),e._v(" "),n("p",[e._v("The presence of "),n("code",[e._v("@WebAppConfiguration")]),e._v(" on your test class instructs the TestContext\nframework (TCF) that a "),n("code",[e._v("WebApplicationContext")]),e._v(" (WAC) should be loaded for your\nintegration tests. In the background, the TCF makes sure that a "),n("code",[e._v("MockServletContext")]),e._v(" is\ncreated and supplied to your test’s WAC. By default, the base resource path for your"),n("code",[e._v("MockServletContext")]),e._v(" is set to "),n("code",[e._v("src/main/webapp")]),e._v(". This is interpreted as a path relative\nto the root of your JVM (normally the path to your project). If you are familiar with the\ndirectory structure of a web application in a Maven project, you know that"),n("code",[e._v("src/main/webapp")]),e._v(" is the default location for the root of your WAR. If you need to\noverride this default, you can provide an alternate path to the "),n("code",[e._v("@WebAppConfiguration")]),e._v("annotation (for example, "),n("code",[e._v('@WebAppConfiguration("src/test/webapp")')]),e._v("). If you wish to\nreference a base resource path from the classpath instead of the file system, you can use\nSpring’s "),n("code",[e._v("classpath:")]),e._v(" prefix.")]),e._v(" "),n("p",[e._v("Note that Spring’s testing support for "),n("code",[e._v("WebApplicationContext")]),e._v(" implementations is on par\nwith its support for standard "),n("code",[e._v("ApplicationContext")]),e._v(" implementations. When testing with a"),n("code",[e._v("WebApplicationContext")]),e._v(", you are free to declare XML configuration files, Groovy scripts,\nor "),n("code",[e._v("@Configuration")]),e._v(" classes by using "),n("code",[e._v("@ContextConfiguration")]),e._v(". You are also free to use\nany other test annotations, such as "),n("code",[e._v("@ActiveProfiles")]),e._v(", "),n("code",[e._v("@TestExecutionListeners")]),e._v(", "),n("code",[e._v("@Sql")]),e._v(","),n("code",[e._v("@Rollback")]),e._v(", and others.")]),e._v(" "),n("p",[e._v("The remaining examples in this section show some of the various configuration options for\nloading a "),n("code",[e._v("WebApplicationContext")]),e._v(". The following example shows the TestContext\nframework’s support for convention over configuration:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n\n// defaults to "file:src/main/webapp"\n@WebAppConfiguration\n\n// detects "WacTests-context.xml" in the same package\n// or static nested @Configuration classes\n@ContextConfiguration\nclass WacTests {\n //...\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n\n// defaults to "file:src/main/webapp"\n@WebAppConfiguration\n\n// detects "WacTests-context.xml" in the same package\n// or static nested @Configuration classes\n@ContextConfiguration\nclass WacTests {\n //...\n}\n')])])]),n("p",[e._v("If you annotate a test class with "),n("code",[e._v("@WebAppConfiguration")]),e._v(" without specifying a resource\nbase path, the resource path effectively defaults to "),n("code",[e._v("file:src/main/webapp")]),e._v(". Similarly,\nif you declare "),n("code",[e._v("@ContextConfiguration")]),e._v(" without specifying resource "),n("code",[e._v("locations")]),e._v(", component"),n("code",[e._v("classes")]),e._v(", or context "),n("code",[e._v("initializers")]),e._v(", Spring tries to detect the presence of your\nconfiguration by using conventions (that is, "),n("code",[e._v("WacTests-context.xml")]),e._v(" in the same package\nas the "),n("code",[e._v("WacTests")]),e._v(" class or static nested "),n("code",[e._v("@Configuration")]),e._v(" classes).")]),e._v(" "),n("p",[e._v("The following example shows how to explicitly declare a resource base path with"),n("code",[e._v("@WebAppConfiguration")]),e._v(" and an XML resource location with "),n("code",[e._v("@ContextConfiguration")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n\n// file system resource\n@WebAppConfiguration("webapp")\n\n// classpath resource\n@ContextConfiguration("/spring/test-servlet-config.xml")\nclass WacTests {\n //...\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n\n// file system resource\n@WebAppConfiguration("webapp")\n\n// classpath resource\n@ContextConfiguration("/spring/test-servlet-config.xml")\nclass WacTests {\n //...\n}\n')])])]),n("p",[e._v("The important thing to note here is the different semantics for paths with these two\nannotations. By default, "),n("code",[e._v("@WebAppConfiguration")]),e._v(" resource paths are file system based,\nwhereas "),n("code",[e._v("@ContextConfiguration")]),e._v(" resource locations are classpath based.")]),e._v(" "),n("p",[e._v("The following example shows that we can override the default resource semantics for both\nannotations by specifying a Spring resource prefix:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n\n// classpath resource\n@WebAppConfiguration("classpath:test-web-resources")\n\n// file system resource\n@ContextConfiguration("file:src/main/webapp/WEB-INF/servlet-config.xml")\nclass WacTests {\n //...\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n\n// classpath resource\n@WebAppConfiguration("classpath:test-web-resources")\n\n// file system resource\n@ContextConfiguration("file:src/main/webapp/WEB-INF/servlet-config.xml")\nclass WacTests {\n //...\n}\n')])])]),n("p",[e._v("Contrast the comments in this example with the previous example.")]),e._v(" "),n("p",[n("a",{attrs:{href:""}}),e._v("Working with Web Mocks")]),e._v(" "),n("p",[e._v("To provide comprehensive web testing support, the TestContext framework has a"),n("code",[e._v("ServletTestExecutionListener")]),e._v(" that is enabled by default. When testing against a"),n("code",[e._v("WebApplicationContext")]),e._v(", this "),n("a",{attrs:{href:"#testcontext-key-abstractions"}},[n("code",[e._v("TestExecutionListener")])]),e._v("sets up default thread-local state by using Spring Web’s "),n("code",[e._v("RequestContextHolder")]),e._v(" before\neach test method and creates a "),n("code",[e._v("MockHttpServletRequest")]),e._v(", a "),n("code",[e._v("MockHttpServletResponse")]),e._v(", and\na "),n("code",[e._v("ServletWebRequest")]),e._v(" based on the base resource path configured with"),n("code",[e._v("@WebAppConfiguration")]),e._v(". "),n("code",[e._v("ServletTestExecutionListener")]),e._v(" also ensures that the"),n("code",[e._v("MockHttpServletResponse")]),e._v(" and "),n("code",[e._v("ServletWebRequest")]),e._v(" can be injected into the test instance,\nand, once the test is complete, it cleans up thread-local state.")]),e._v(" "),n("p",[e._v("Once you have a "),n("code",[e._v("WebApplicationContext")]),e._v(" loaded for your test, you might find that you\nneed to interact with the web mocks — for example, to set up your test fixture or to\nperform assertions after invoking your web component. The following example shows which\nmocks can be autowired into your test instance. Note that the "),n("code",[e._v("WebApplicationContext")]),e._v(" and"),n("code",[e._v("MockServletContext")]),e._v(" are both cached across the test suite, whereas the other mocks are\nmanaged per test method by the "),n("code",[e._v("ServletTestExecutionListener")]),e._v(".")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitWebConfig\nclass WacTests {\n\n @Autowired\n WebApplicationContext wac; // cached\n\n @Autowired\n MockServletContext servletContext; // cached\n\n @Autowired\n MockHttpSession session;\n\n @Autowired\n MockHttpServletRequest request;\n\n @Autowired\n MockHttpServletResponse response;\n\n @Autowired\n ServletWebRequest webRequest;\n\n //...\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitWebConfig\nclass WacTests {\n\n @Autowired\n lateinit var wac: WebApplicationContext // cached\n\n @Autowired\n lateinit var servletContext: MockServletContext // cached\n\n @Autowired\n lateinit var session: MockHttpSession\n\n @Autowired\n lateinit var request: MockHttpServletRequest\n\n @Autowired\n lateinit var response: MockHttpServletResponse\n\n @Autowired\n lateinit var webRequest: ServletWebRequest\n\n //...\n}\n")])])]),n("h5",{attrs:{id:"context-caching"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#context-caching"}},[e._v("#")]),e._v(" Context Caching")]),e._v(" "),n("p",[e._v("Once the TestContext framework loads an "),n("code",[e._v("ApplicationContext")]),e._v(" (or "),n("code",[e._v("WebApplicationContext")]),e._v(")\nfor a test, that context is cached and reused for all subsequent tests that declare the\nsame unique context configuration within the same test suite. To understand how caching\nworks, it is important to understand what is meant by “unique” and “test suite.”")]),e._v(" "),n("p",[e._v("An "),n("code",[e._v("ApplicationContext")]),e._v(" can be uniquely identified by the combination of configuration\nparameters that is used to load it. Consequently, the unique combination of configuration\nparameters is used to generate a key under which the context is cached. The TestContext\nframework uses the following configuration parameters to build the context cache key:")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("locations")]),e._v(" (from "),n("code",[e._v("@ContextConfiguration")]),e._v(")")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("classes")]),e._v(" (from "),n("code",[e._v("@ContextConfiguration")]),e._v(")")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("contextInitializerClasses")]),e._v(" (from "),n("code",[e._v("@ContextConfiguration")]),e._v(")")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("contextCustomizers")]),e._v(" (from "),n("code",[e._v("ContextCustomizerFactory")]),e._v(") – this includes"),n("code",[e._v("@DynamicPropertySource")]),e._v(" methods as well as various features from Spring Boot’s\ntesting support such as "),n("code",[e._v("@MockBean")]),e._v(" and "),n("code",[e._v("@SpyBean")]),e._v(".")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("contextLoader")]),e._v(" (from "),n("code",[e._v("@ContextConfiguration")]),e._v(")")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("parent")]),e._v(" (from "),n("code",[e._v("@ContextHierarchy")]),e._v(")")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("activeProfiles")]),e._v(" (from "),n("code",[e._v("@ActiveProfiles")]),e._v(")")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("propertySourceLocations")]),e._v(" (from "),n("code",[e._v("@TestPropertySource")]),e._v(")")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("propertySourceProperties")]),e._v(" (from "),n("code",[e._v("@TestPropertySource")]),e._v(")")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("resourceBasePath")]),e._v(" (from "),n("code",[e._v("@WebAppConfiguration")]),e._v(")")])])]),e._v(" "),n("p",[e._v("For example, if "),n("code",[e._v("TestClassA")]),e._v(" specifies "),n("code",[e._v('{"app-config.xml", "test-config.xml"}')]),e._v(" for the"),n("code",[e._v("locations")]),e._v(" (or "),n("code",[e._v("value")]),e._v(") attribute of "),n("code",[e._v("@ContextConfiguration")]),e._v(", the TestContext framework\nloads the corresponding "),n("code",[e._v("ApplicationContext")]),e._v(" and stores it in a "),n("code",[e._v("static")]),e._v(" context cache\nunder a key that is based solely on those locations. So, if "),n("code",[e._v("TestClassB")]),e._v(" also defines"),n("code",[e._v('{"app-config.xml", "test-config.xml"}')]),e._v(" for its locations (either explicitly or\nimplicitly through inheritance) but does not define "),n("code",[e._v("@WebAppConfiguration")]),e._v(", a different"),n("code",[e._v("ContextLoader")]),e._v(", different active profiles, different context initializers, different\ntest property sources, or a different parent context, then the same "),n("code",[e._v("ApplicationContext")]),e._v("is shared by both test classes. This means that the setup cost for loading an application\ncontext is incurred only once (per test suite), and subsequent test execution is much\nfaster.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Test suites and forked processes"),n("br"),n("br"),e._v("The Spring TestContext framework stores application contexts in a static cache. This"),n("br"),e._v("means that the context is literally stored in a "),n("code",[e._v("static")]),e._v(" variable. In other words, if"),n("br"),e._v("tests run in separate processes, the static cache is cleared between each test"),n("br"),e._v("execution, which effectively disables the caching mechanism."),n("br"),n("br"),e._v("To benefit from the caching mechanism, all tests must run within the same process or test"),n("br"),e._v("suite. This can be achieved by executing all tests as a group within an IDE. Similarly,"),n("br"),e._v("when executing tests with a build framework such as Ant, Maven, or Gradle, it is"),n("br"),e._v("important to make sure that the build framework does not fork between tests. For example,"),n("br"),e._v("if the"),n("a",{attrs:{href:"https://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html#forkMode",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("forkMode")]),n("OutboundLink")],1),e._v("for the Maven Surefire plug-in is set to "),n("code",[e._v("always")]),e._v(" or "),n("code",[e._v("pertest")]),e._v(", the TestContext framework"),n("br"),e._v("cannot cache application contexts between test classes, and the build process runs"),n("br"),e._v("significantly more slowly as a result.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("The size of the context cache is bounded with a default maximum size of 32. Whenever the\nmaximum size is reached, a least recently used (LRU) eviction policy is used to evict and\nclose stale contexts. You can configure the maximum size from the command line or a build\nscript by setting a JVM system property named "),n("code",[e._v("spring.test.context.cache.maxSize")]),e._v(". As an\nalternative, you can set the same property via the"),n("RouterLink",{attrs:{to:"/en/spring-framework/appendix.html#appendix-spring-properties"}},[n("code",[e._v("SpringProperties")])]),e._v(" mechanism.")],1),e._v(" "),n("p",[e._v("Since having a large number of application contexts loaded within a given test suite can\ncause the suite to take an unnecessarily long time to run, it is often beneficial to\nknow exactly how many contexts have been loaded and cached. To view the statistics for\nthe underlying context cache, you can set the log level for the"),n("code",[e._v("org.springframework.test.context.cache")]),e._v(" logging category to "),n("code",[e._v("DEBUG")]),e._v(".")]),e._v(" "),n("p",[e._v("In the unlikely case that a test corrupts the application context and requires reloading\n(for example, by modifying a bean definition or the state of an application object), you\ncan annotate your test class or test method with "),n("code",[e._v("@DirtiesContext")]),e._v(" (see the discussion of"),n("code",[e._v("@DirtiesContext")]),e._v(" in "),n("a",{attrs:{href:"#spring-testing-annotation-dirtiescontext"}},[e._v("Spring Testing\nAnnotations")]),e._v("). This instructs Spring to remove the context from the cache and rebuild\nthe application context before running the next test that requires the same application\ncontext. Note that support for the "),n("code",[e._v("@DirtiesContext")]),e._v(" annotation is provided by the"),n("code",[e._v("DirtiesContextBeforeModesTestExecutionListener")]),e._v(" and the"),n("code",[e._v("DirtiesContextTestExecutionListener")]),e._v(", which are enabled by default.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("ApplicationContext lifecycle and console logging"),n("br"),n("br"),e._v("When you need to debug a test executed with the Spring TestContext Framework, it can be"),n("br"),e._v("useful to analyze the console output (that is, output to the "),n("code",[e._v("SYSOUT")]),e._v(" and "),n("code",[e._v("SYSERR")]),e._v("streams). Some build tools and IDEs are able to associate console output with a given"),n("br"),e._v("test; however, some console output cannot be easily associated with a given test."),n("br"),n("br"),e._v("With regard to console logging triggered by the Spring Framework itself or by components"),n("br"),e._v("registered in the "),n("code",[e._v("ApplicationContext")]),e._v(", it is important to understand the lifecycle of an"),n("code",[e._v("ApplicationContext")]),e._v(" that has been loaded by the Spring TestContext Framework within a"),n("br"),e._v("test suite."),n("br"),n("br"),e._v("The "),n("code",[e._v("ApplicationContext")]),e._v(" for a test is typically loaded when an instance of the test"),n("br"),e._v("class is being prepared — for example, to perform dependency injection into "),n("code",[e._v("@Autowired")]),e._v("fields of the test instance. This means that any console logging triggered during the"),n("br"),e._v("initialization of the "),n("code",[e._v("ApplicationContext")]),e._v(" typically cannot be associated with an"),n("br"),e._v("individual test method. However, if the context is closed immediately before the"),n("br"),e._v("execution of a test method according to "),n("a",{attrs:{href:"#spring-testing-annotation-dirtiescontext"}},[n("code",[e._v("@DirtiesContext")])]),e._v("semantics, a new instance of the context will be loaded just prior to execution of the"),n("br"),e._v("test method. In the latter scenario, an IDE or build tool may potentially associate"),n("br"),e._v("console logging with the individual test method."),n("br"),n("br"),e._v("The "),n("code",[e._v("ApplicationContext")]),e._v(" for a test can be closed via one of the following scenarios."),n("br"),n("br"),e._v("* The context is closed according to "),n("code",[e._v("@DirtiesContext")]),e._v(" semantics."),n("br"),n("br"),e._v("* The context is closed because it has been automatically evicted from the cache"),n("br"),e._v(" according to the LRU eviction policy."),n("br"),n("br"),e._v("* The context is closed via a JVM shutdown hook when the JVM for the test suite"),n("br"),e._v(" terminates."),n("br"),n("br"),e._v("If the context is closed according to "),n("code",[e._v("@DirtiesContext")]),e._v(" semantics after a particular test"),n("br"),e._v("method, an IDE or build tool may potentially associate console logging with the"),n("br"),e._v("individual test method. If the context is closed according to "),n("code",[e._v("@DirtiesContext")]),e._v(" semantics"),n("br"),e._v("after a test class, any console logging triggered during the shutdown of the"),n("code",[e._v("ApplicationContext")]),e._v(" cannot be associated with an individual test method. Similarly, any"),n("br"),e._v("console logging triggered during the shutdown phase via a JVM shutdown hook cannot be"),n("br"),e._v("associated with an individual test method."),n("br"),n("br"),e._v("When a Spring "),n("code",[e._v("ApplicationContext")]),e._v(" is closed via a JVM shutdown hook, callbacks executed"),n("br"),e._v("during the shutdown phase are executed on a thread named "),n("code",[e._v("SpringContextShutdownHook")]),e._v(". So,"),n("br"),e._v("if you wish to disable console logging triggered when the "),n("code",[e._v("ApplicationContext")]),e._v(" is closed"),n("br"),e._v("via a JVM shutdown hook, you may be able to register a custom filter with your logging"),n("br"),e._v("framework that allows you to ignore any logging initiated by that thread.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"context-hierarchies"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#context-hierarchies"}},[e._v("#")]),e._v(" Context Hierarchies")]),e._v(" "),n("p",[e._v("When writing integration tests that rely on a loaded Spring "),n("code",[e._v("ApplicationContext")]),e._v(", it is\noften sufficient to test against a single context. However, there are times when it is\nbeneficial or even necessary to test against a hierarchy of "),n("code",[e._v("ApplicationContext")]),e._v("instances. For example, if you are developing a Spring MVC web application, you typically\nhave a root "),n("code",[e._v("WebApplicationContext")]),e._v(" loaded by Spring’s "),n("code",[e._v("ContextLoaderListener")]),e._v(" and a\nchild "),n("code",[e._v("WebApplicationContext")]),e._v(" loaded by Spring’s "),n("code",[e._v("DispatcherServlet")]),e._v(". This results in a\nparent-child context hierarchy where shared components and infrastructure configuration\nare declared in the root context and consumed in the child context by web-specific\ncomponents. Another use case can be found in Spring Batch applications, where you often\nhave a parent context that provides configuration for shared batch infrastructure and a\nchild context for the configuration of a specific batch job.")]),e._v(" "),n("p",[e._v("You can write integration tests that use context hierarchies by declaring context\nconfiguration with the "),n("code",[e._v("@ContextHierarchy")]),e._v(" annotation, either on an individual test class\nor within a test class hierarchy. If a context hierarchy is declared on multiple classes\nwithin a test class hierarchy, you can also merge or override the context configuration\nfor a specific, named level in the context hierarchy. When merging configuration for a\ngiven level in the hierarchy, the configuration resource type (that is, XML configuration\nfiles or component classes) must be consistent. Otherwise, it is perfectly acceptable to\nhave different levels in a context hierarchy configured using different resource types.")]),e._v(" "),n("p",[e._v("The remaining JUnit Jupiter based examples in this section show common configuration\nscenarios for integration tests that require the use of context hierarchies.")]),e._v(" "),n("p",[e._v("Single test class with context hierarchy")]),e._v(" "),n("p",[n("code",[e._v("ControllerIntegrationTests")]),e._v(" represents a typical integration testing scenario for a\nSpring MVC web application by declaring a context hierarchy that consists of two levels,\none for the root "),n("code",[e._v("WebApplicationContext")]),e._v(" (loaded by using the "),n("code",[e._v("TestAppConfig``@Configuration")]),e._v(" class) and one for the dispatcher servlet "),n("code",[e._v("WebApplicationContext")]),e._v("(loaded by using the "),n("code",[e._v("WebConfig")]),e._v(" "),n("code",[e._v("@Configuration")]),e._v(" class). The "),n("code",[e._v("WebApplicationContext")]),e._v("that is autowired into the test instance is the one for the child context (that is, the\nlowest context in the hierarchy). The following listing shows this configuration scenario:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ExtendWith(SpringExtension.class)\n@WebAppConfiguration\n@ContextHierarchy({\n @ContextConfiguration(classes = TestAppConfig.class),\n @ContextConfiguration(classes = WebConfig.class)\n})\nclass ControllerIntegrationTests {\n\n @Autowired\n WebApplicationContext wac;\n\n // ...\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@ExtendWith(SpringExtension::class)\n@WebAppConfiguration\n@ContextHierarchy(\n ContextConfiguration(classes = [TestAppConfig::class]),\n ContextConfiguration(classes = [WebConfig::class]))\nclass ControllerIntegrationTests {\n\n @Autowired\n lateinit var wac: WebApplicationContext\n\n // ...\n}\n")])])]),n("p",[e._v("Class hierarchy with implicit parent context")]),e._v(" "),n("p",[e._v("The test classes in this example define a context hierarchy within a test class\nhierarchy. "),n("code",[e._v("AbstractWebTests")]),e._v(" declares the configuration for a root"),n("code",[e._v("WebApplicationContext")]),e._v(" in a Spring-powered web application. Note, however, that"),n("code",[e._v("AbstractWebTests")]),e._v(" does not declare "),n("code",[e._v("@ContextHierarchy")]),e._v(". Consequently, subclasses of"),n("code",[e._v("AbstractWebTests")]),e._v(" can optionally participate in a context hierarchy or follow the\nstandard semantics for "),n("code",[e._v("@ContextConfiguration")]),e._v(". "),n("code",[e._v("SoapWebServiceTests")]),e._v(" and"),n("code",[e._v("RestWebServiceTests")]),e._v(" both extend "),n("code",[e._v("AbstractWebTests")]),e._v(" and define a context hierarchy by\nusing "),n("code",[e._v("@ContextHierarchy")]),e._v(". The result is that three application contexts are loaded (one\nfor each declaration of "),n("code",[e._v("@ContextConfiguration")]),e._v("), and the application context loaded\nbased on the configuration in "),n("code",[e._v("AbstractWebTests")]),e._v(" is set as the parent context for each of\nthe contexts loaded for the concrete subclasses. The following listing shows this\nconfiguration scenario:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n@WebAppConfiguration\n@ContextConfiguration("file:src/main/webapp/WEB-INF/applicationContext.xml")\npublic abstract class AbstractWebTests {}\n\n@ContextHierarchy(@ContextConfiguration("/spring/soap-ws-config.xml"))\npublic class SoapWebServiceTests extends AbstractWebTests {}\n\n@ContextHierarchy(@ContextConfiguration("/spring/rest-ws-config.xml"))\npublic class RestWebServiceTests extends AbstractWebTests {}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n@WebAppConfiguration\n@ContextConfiguration("file:src/main/webapp/WEB-INF/applicationContext.xml")\nabstract class AbstractWebTests\n\n@ContextHierarchy(ContextConfiguration("/spring/soap-ws-config.xml"))\nclass SoapWebServiceTests : AbstractWebTests()\n\n@ContextHierarchy(ContextConfiguration("/spring/rest-ws-config.xml"))\nclass RestWebServiceTests : AbstractWebTests()\n')])])]),n("p",[e._v("Class hierarchy with merged context hierarchy configuration")]),e._v(" "),n("p",[e._v("The classes in this example show the use of named hierarchy levels in order to merge the\nconfiguration for specific levels in a context hierarchy. "),n("code",[e._v("BaseTests")]),e._v(" defines two levels\nin the hierarchy, "),n("code",[e._v("parent")]),e._v(" and "),n("code",[e._v("child")]),e._v(". "),n("code",[e._v("ExtendedTests")]),e._v(" extends "),n("code",[e._v("BaseTests")]),e._v(" and instructs\nthe Spring TestContext Framework to merge the context configuration for the "),n("code",[e._v("child")]),e._v("hierarchy level, by ensuring that the names declared in the "),n("code",[e._v("name")]),e._v(" attribute in"),n("code",[e._v("@ContextConfiguration")]),e._v(" are both "),n("code",[e._v("child")]),e._v(". The result is that three application contexts\nare loaded: one for "),n("code",[e._v("/app-config.xml")]),e._v(", one for "),n("code",[e._v("/user-config.xml")]),e._v(", and one for"),n("code",[e._v('{"/user-config.xml", "/order-config.xml"}')]),e._v(". As with the previous example, the\napplication context loaded from "),n("code",[e._v("/app-config.xml")]),e._v(" is set as the parent context for the\ncontexts loaded from "),n("code",[e._v("/user-config.xml")]),e._v(" and "),n("code",[e._v('{"/user-config.xml", "/order-config.xml"}')]),e._v(".\nThe following listing shows this configuration scenario:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n@ContextHierarchy({\n @ContextConfiguration(name = "parent", locations = "/app-config.xml"),\n @ContextConfiguration(name = "child", locations = "/user-config.xml")\n})\nclass BaseTests {}\n\n@ContextHierarchy(\n @ContextConfiguration(name = "child", locations = "/order-config.xml")\n)\nclass ExtendedTests extends BaseTests {}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n@ContextHierarchy(\n ContextConfiguration(name = "parent", locations = ["/app-config.xml"]),\n ContextConfiguration(name = "child", locations = ["/user-config.xml"]))\nopen class BaseTests {}\n\n@ContextHierarchy(\n ContextConfiguration(name = "child", locations = ["/order-config.xml"])\n)\nclass ExtendedTests : BaseTests() {}\n')])])]),n("p",[e._v("Class hierarchy with overridden context hierarchy configuration")]),e._v(" "),n("p",[e._v("In contrast to the previous example, this example demonstrates how to override the\nconfiguration for a given named level in a context hierarchy by setting the"),n("code",[e._v("inheritLocations")]),e._v(" flag in "),n("code",[e._v("@ContextConfiguration")]),e._v(" to "),n("code",[e._v("false")]),e._v(". Consequently, the\napplication context for "),n("code",[e._v("ExtendedTests")]),e._v(" is loaded only from "),n("code",[e._v("/test-user-config.xml")]),e._v(" and\nhas its parent set to the context loaded from "),n("code",[e._v("/app-config.xml")]),e._v(". The following listing\nshows this configuration scenario:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n@ContextHierarchy({\n @ContextConfiguration(name = "parent", locations = "/app-config.xml"),\n @ContextConfiguration(name = "child", locations = "/user-config.xml")\n})\nclass BaseTests {}\n\n@ContextHierarchy(\n @ContextConfiguration(\n name = "child",\n locations = "/test-user-config.xml",\n inheritLocations = false\n))\nclass ExtendedTests extends BaseTests {}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n@ContextHierarchy(\n ContextConfiguration(name = "parent", locations = ["/app-config.xml"]),\n ContextConfiguration(name = "child", locations = ["/user-config.xml"]))\nopen class BaseTests {}\n\n@ContextHierarchy(\n ContextConfiguration(\n name = "child",\n locations = ["/test-user-config.xml"],\n inheritLocations = false\n ))\nclass ExtendedTests : BaseTests() {}\n')])])]),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Dirtying a context within a context hierarchy"),n("br"),n("br"),e._v("If you use "),n("code",[e._v("@DirtiesContext")]),e._v(" in a test whose context is configured as part of a"),n("br"),e._v("context hierarchy, you can use the "),n("code",[e._v("hierarchyMode")]),e._v(" flag to control how the context cache"),n("br"),e._v("is cleared. For further details, see the discussion of "),n("code",[e._v("@DirtiesContext")]),e._v(" in"),n("a",{attrs:{href:"#spring-testing-annotation-dirtiescontext"}},[e._v("Spring Testing Annotations")]),e._v(" and the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/annotation/DirtiesContext.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@DirtiesContext")]),n("OutboundLink")],1),e._v(" javadoc.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h4",{attrs:{id:"_3-5-7-dependency-injection-of-test-fixtures"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-7-dependency-injection-of-test-fixtures"}},[e._v("#")]),e._v(" 3.5.7. Dependency Injection of Test Fixtures")]),e._v(" "),n("p",[e._v("When you use the "),n("code",[e._v("DependencyInjectionTestExecutionListener")]),e._v(" (which is configured by\ndefault), the dependencies of your test instances are injected from beans in the\napplication context that you configured with "),n("code",[e._v("@ContextConfiguration")]),e._v(" or related\nannotations. You may use setter injection, field injection, or both, depending on\nwhich annotations you choose and whether you place them on setter methods or fields.\nIf you are using JUnit Jupiter you may also optionally use constructor injection\n(see "),n("a",{attrs:{href:"#testcontext-junit-jupiter-di"}},[e._v("Dependency Injection with "),n("code",[e._v("SpringExtension")])]),e._v("). For consistency with Spring’s annotation-based\ninjection support, you may also use Spring’s "),n("code",[e._v("@Autowired")]),e._v(" annotation or the "),n("code",[e._v("@Inject")]),e._v("annotation from JSR-330 for field and setter injection.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("For testing frameworks other than JUnit Jupiter, the TestContext framework does not"),n("br"),e._v("participate in instantiation of the test class. Thus, the use of "),n("code",[e._v("@Autowired")]),e._v(" or"),n("code",[e._v("@Inject")]),e._v(" for constructors has no effect for test classes.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Although field injection is discouraged in production code, field injection is"),n("br"),e._v("actually quite natural in test code. The rationale for the difference is that you will"),n("br"),e._v("never instantiate your test class directly. Consequently, there is no need to be able to"),n("br"),e._v("invoke a "),n("code",[e._v("public")]),e._v(" constructor or setter method on your test class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Because "),n("code",[e._v("@Autowired")]),e._v(" is used to perform "),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#beans-factory-autowire"}},[e._v("autowiring by\ntype")]),e._v(", if you have multiple bean definitions of the same type, you cannot rely on this\napproach for those particular beans. In that case, you can use "),n("code",[e._v("@Autowired")]),e._v(" in\nconjunction with "),n("code",[e._v("@Qualifier")]),e._v(". You can also choose to use "),n("code",[e._v("@Inject")]),e._v(" in conjunction with"),n("code",[e._v("@Named")]),e._v(". Alternatively, if your test class has access to its "),n("code",[e._v("ApplicationContext")]),e._v(", you\ncan perform an explicit lookup by using (for example) a call to"),n("code",[e._v('applicationContext.getBean("titleRepository", TitleRepository.class)')]),e._v(".")],1),e._v(" "),n("p",[e._v("If you do not want dependency injection applied to your test instances, do not annotate\nfields or setter methods with "),n("code",[e._v("@Autowired")]),e._v(" or "),n("code",[e._v("@Inject")]),e._v(". Alternatively, you can disable\ndependency injection altogether by explicitly configuring your class with"),n("code",[e._v("@TestExecutionListeners")]),e._v(" and omitting "),n("code",[e._v("DependencyInjectionTestExecutionListener.class")]),e._v("from the list of listeners.")]),e._v(" "),n("p",[e._v("Consider the scenario of testing a "),n("code",[e._v("HibernateTitleRepository")]),e._v(" class, as outlined in the"),n("a",{attrs:{href:"#integration-testing-goals"}},[e._v("Goals")]),e._v(" section. The next two code listings demonstrate the\nuse of "),n("code",[e._v("@Autowired")]),e._v(" on fields and setter methods. The application context configuration\nis presented after all sample code listings.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("The dependency injection behavior in the following code listings is not specific to JUnit"),n("br"),e._v("Jupiter. The same DI techniques can be used in conjunction with any supported testing"),n("br"),e._v("framework."),n("br"),n("br"),e._v("The following examples make calls to static assertion methods, such as "),n("code",[e._v("assertNotNull()")]),e._v(","),n("br"),e._v("but without prepending the call with "),n("code",[e._v("Assertions")]),e._v(". In such cases, assume that the method"),n("br"),e._v("was properly imported through an "),n("code",[e._v("import static")]),e._v(" declaration that is not shown in the"),n("br"),e._v("example.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("The first code listing shows a JUnit Jupiter based implementation of the test class that\nuses "),n("code",[e._v("@Autowired")]),e._v(" for field injection:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n// specifies the Spring configuration to load for this test fixture\n@ContextConfiguration("repository-config.xml")\nclass HibernateTitleRepositoryTests {\n\n // this instance will be dependency injected by type\n @Autowired\n HibernateTitleRepository titleRepository;\n\n @Test\n void findById() {\n Title title = titleRepository.findById(new Long(10));\n assertNotNull(title);\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n// specifies the Spring configuration to load for this test fixture\n@ContextConfiguration("repository-config.xml")\nclass HibernateTitleRepositoryTests {\n\n // this instance will be dependency injected by type\n @Autowired\n lateinit var titleRepository: HibernateTitleRepository\n\n @Test\n fun findById() {\n val title = titleRepository.findById(10)\n assertNotNull(title)\n }\n}\n')])])]),n("p",[e._v("Alternatively, you can configure the class to use "),n("code",[e._v("@Autowired")]),e._v(" for setter injection, as\nfollows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n// specifies the Spring configuration to load for this test fixture\n@ContextConfiguration("repository-config.xml")\nclass HibernateTitleRepositoryTests {\n\n // this instance will be dependency injected by type\n HibernateTitleRepository titleRepository;\n\n @Autowired\n void setTitleRepository(HibernateTitleRepository titleRepository) {\n this.titleRepository = titleRepository;\n }\n\n @Test\n void findById() {\n Title title = titleRepository.findById(new Long(10));\n assertNotNull(title);\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension::class)\n// specifies the Spring configuration to load for this test fixture\n@ContextConfiguration("repository-config.xml")\nclass HibernateTitleRepositoryTests {\n\n // this instance will be dependency injected by type\n lateinit var titleRepository: HibernateTitleRepository\n\n @Autowired\n fun setTitleRepository(titleRepository: HibernateTitleRepository) {\n this.titleRepository = titleRepository\n }\n\n @Test\n fun findById() {\n val title = titleRepository.findById(10)\n assertNotNull(title)\n }\n}\n')])])]),n("p",[e._v("The preceding code listings use the same XML context file referenced by the"),n("code",[e._v("@ContextConfiguration")]),e._v(" annotation (that is, "),n("code",[e._v("repository-config.xml")]),e._v("). The following\nshows this configuration:")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('\n\n\n \x3c!-- this bean will be injected into the HibernateTitleRepositoryTests class --\x3e\n \n \n \n\n \n \x3c!-- configuration elided for brevity --\x3e\n \n\n\n')])])]),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("If you are extending from a Spring-provided test base class that happens to use"),n("code",[e._v("@Autowired")]),e._v(" on one of its setter methods, you might have multiple beans of the affected"),n("br"),e._v("type defined in your application context (for example, multiple "),n("code",[e._v("DataSource")]),e._v(" beans). In"),n("br"),e._v("such a case, you can override the setter method and use the "),n("code",[e._v("@Qualifier")]),e._v(" annotation to"),n("br"),e._v("indicate a specific target bean, as follows (but make sure to delegate to the overridden"),n("br"),e._v("method in the superclass as well):"),n("br"),n("br"),e._v("Java"),n("br"),n("br"),n("code",[e._v('
// ...

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

// ...
')]),n("br"),n("br"),e._v("Kotlin"),n("br"),n("br"),n("code",[e._v('
// ...

@Autowired
override fun setDataSource(@Qualifier("myDataSource") dataSource: DataSource) {
super.setDataSource(dataSource)
}

// ...
')]),n("br"),n("br"),e._v("The specified qualifier value indicates the specific "),n("code",[e._v("DataSource")]),e._v(" bean to inject,"),n("br"),e._v("narrowing the set of type matches to a specific bean. Its value is matched against"),n("code",[e._v("")]),e._v(" declarations within the corresponding "),n("code",[e._v("")]),e._v(" definitions. The bean name"),n("br"),e._v("is used as a fallback qualifier value, so you can effectively also point to a specific"),n("br"),e._v("bean by name there (as shown earlier, assuming that "),n("code",[e._v("myDataSource")]),e._v(" is the bean "),n("code",[e._v("id")]),e._v(").")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h4",{attrs:{id:"_3-5-8-testing-request-and-session-scoped-beans"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-8-testing-request-and-session-scoped-beans"}},[e._v("#")]),e._v(" 3.5.8. Testing Request- and Session-scoped Beans")]),e._v(" "),n("p",[e._v("Spring has supported "),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#beans-factory-scopes-other"}},[e._v("Request- and session-scoped\nbeans")]),e._v(" since the early years, and you can test your request-scoped and session-scoped\nbeans by following these steps:")],1),e._v(" "),n("ul",[n("li",[n("p",[e._v("Ensure that a "),n("code",[e._v("WebApplicationContext")]),e._v(" is loaded for your test by annotating your test\nclass with "),n("code",[e._v("@WebAppConfiguration")]),e._v(".")])]),e._v(" "),n("li",[n("p",[e._v("Inject the mock request or session into your test instance and prepare your test\nfixture as appropriate.")])]),e._v(" "),n("li",[n("p",[e._v("Invoke your web component that you retrieved from the configured"),n("code",[e._v("WebApplicationContext")]),e._v(" (with dependency injection).")])]),e._v(" "),n("li",[n("p",[e._v("Perform assertions against the mocks.")])])]),e._v(" "),n("p",[e._v("The next code snippet shows the XML configuration for a login use case. Note that the"),n("code",[e._v("userService")]),e._v(" bean has a dependency on a request-scoped "),n("code",[e._v("loginAction")]),e._v(" bean. Also, the"),n("code",[e._v("LoginAction")]),e._v(" is instantiated by using "),n("RouterLink",{attrs:{to:"/en/spring-framework/core.html#expressions"}},[e._v("SpEL expressions")]),e._v(" that\nretrieve the username and password from the current HTTP request. In our test, we want to\nconfigure these request parameters through the mock managed by the TestContext framework.\nThe following listing shows the configuration for this use case:")],1),e._v(" "),n("p",[e._v("Request-scoped bean configuration")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('\n\n \n\n \n \n \n\n\n')])])]),n("p",[e._v("In "),n("code",[e._v("RequestScopedBeanTests")]),e._v(", we inject both the "),n("code",[e._v("UserService")]),e._v(" (that is, the subject under\ntest) and the "),n("code",[e._v("MockHttpServletRequest")]),e._v(" into our test instance. Within our"),n("code",[e._v("requestScope()")]),e._v(" test method, we set up our test fixture by setting request parameters in\nthe provided "),n("code",[e._v("MockHttpServletRequest")]),e._v(". When the "),n("code",[e._v("loginUser()")]),e._v(" method is invoked on our"),n("code",[e._v("userService")]),e._v(", we are assured that the user service has access to the request-scoped"),n("code",[e._v("loginAction")]),e._v(" for the current "),n("code",[e._v("MockHttpServletRequest")]),e._v(" (that is, the one in which we just\nset parameters). We can then perform assertions against the results based on the known\ninputs for the username and password. The following listing shows how to do so:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitWebConfig\nclass RequestScopedBeanTests {\n\n @Autowired UserService userService;\n @Autowired MockHttpServletRequest request;\n\n @Test\n void requestScope() {\n request.setParameter("user", "enigma");\n request.setParameter("pswd", "$pr!ng");\n\n LoginResults results = userService.loginUser();\n // assert results\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitWebConfig\nclass RequestScopedBeanTests {\n\n @Autowired lateinit var userService: UserService\n @Autowired lateinit var request: MockHttpServletRequest\n\n @Test\n fun requestScope() {\n request.setParameter("user", "enigma")\n request.setParameter("pswd", "\\$pr!ng")\n\n val results = userService.loginUser()\n // assert results\n }\n}\n')])])]),n("p",[e._v("The following code snippet is similar to the one we saw earlier for a request-scoped\nbean. However, this time, the "),n("code",[e._v("userService")]),e._v(" bean has a dependency on a session-scoped"),n("code",[e._v("userPreferences")]),e._v(" bean. Note that the "),n("code",[e._v("UserPreferences")]),e._v(" bean is instantiated by using a\nSpEL expression that retrieves the theme from the current HTTP session. In our test, we\nneed to configure a theme in the mock session managed by the TestContext framework. The\nfollowing example shows how to do so:")]),e._v(" "),n("p",[e._v("Session-scoped bean configuration")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('\n\n \n\n \n \n \n\n\n')])])]),n("p",[e._v("In "),n("code",[e._v("SessionScopedBeanTests")]),e._v(", we inject the "),n("code",[e._v("UserService")]),e._v(" and the "),n("code",[e._v("MockHttpSession")]),e._v(" into\nour test instance. Within our "),n("code",[e._v("sessionScope()")]),e._v(" test method, we set up our test fixture by\nsetting the expected "),n("code",[e._v("theme")]),e._v(" attribute in the provided "),n("code",[e._v("MockHttpSession")]),e._v(". When the"),n("code",[e._v("processUserPreferences()")]),e._v(" method is invoked on our "),n("code",[e._v("userService")]),e._v(", we are assured that\nthe user service has access to the session-scoped "),n("code",[e._v("userPreferences")]),e._v(" for the current"),n("code",[e._v("MockHttpSession")]),e._v(", and we can perform assertions against the results based on the\nconfigured theme. The following example shows how to do so:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitWebConfig\nclass SessionScopedBeanTests {\n\n @Autowired UserService userService;\n @Autowired MockHttpSession session;\n\n @Test\n void sessionScope() throws Exception {\n session.setAttribute("theme", "blue");\n\n Results results = userService.processUserPreferences();\n // assert results\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitWebConfig\nclass SessionScopedBeanTests {\n\n @Autowired lateinit var userService: UserService\n @Autowired lateinit var session: MockHttpSession\n\n @Test\n fun sessionScope() {\n session.setAttribute("theme", "blue")\n\n val results = userService.processUserPreferences()\n // assert results\n }\n}\n')])])]),n("h4",{attrs:{id:"_3-5-9-transaction-management"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-9-transaction-management"}},[e._v("#")]),e._v(" 3.5.9. Transaction Management")]),e._v(" "),n("p",[e._v("In the TestContext framework, transactions are managed by the"),n("code",[e._v("TransactionalTestExecutionListener")]),e._v(", which is configured by default, even if you do not\nexplicitly declare "),n("code",[e._v("@TestExecutionListeners")]),e._v(" on your test class. To enable support for\ntransactions, however, you must configure a "),n("code",[e._v("PlatformTransactionManager")]),e._v(" bean in the"),n("code",[e._v("ApplicationContext")]),e._v(" that is loaded with "),n("code",[e._v("@ContextConfiguration")]),e._v(" semantics (further\ndetails are provided later). In addition, you must declare Spring’s "),n("code",[e._v("@Transactional")]),e._v("annotation either at the class or the method level for your tests.")]),e._v(" "),n("h5",{attrs:{id:"test-managed-transactions"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#test-managed-transactions"}},[e._v("#")]),e._v(" Test-managed Transactions")]),e._v(" "),n("p",[e._v("Test-managed transactions are transactions that are managed declaratively by using the"),n("code",[e._v("TransactionalTestExecutionListener")]),e._v(" or programmatically by using "),n("code",[e._v("TestTransaction")]),e._v("(described later). You should not confuse such transactions with Spring-managed\ntransactions (those managed directly by Spring within the "),n("code",[e._v("ApplicationContext")]),e._v(" loaded for\ntests) or application-managed transactions (those managed programmatically within\napplication code that is invoked by tests). Spring-managed and application-managed\ntransactions typically participate in test-managed transactions. However, you should use\ncaution if Spring-managed or application-managed transactions are configured with any\npropagation type other than "),n("code",[e._v("REQUIRED")]),e._v(" or "),n("code",[e._v("SUPPORTS")]),e._v(" (see the discussion on"),n("RouterLink",{attrs:{to:"/en/spring-framework/data-access.html#tx-propagation"}},[e._v("transaction propagation")]),e._v(" for details).")],1),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Preemptive timeouts and test-managed transactions"),n("br"),n("br"),e._v("Caution must be taken when using any form of preemptive timeouts from a testing framework"),n("br"),e._v("in conjunction with Spring’s test-managed transactions."),n("br"),n("br"),e._v("Specifically, Spring’s testing support binds transaction state to the current thread (via"),n("br"),e._v("a "),n("code",[e._v("java.lang.ThreadLocal")]),e._v(" variable) "),n("em",[e._v("before")]),e._v(" the current test method is invoked. If a"),n("br"),e._v("testing framework invokes the current test method in a new thread in order to support a"),n("br"),e._v("preemptive timeout, any actions performed within the current test method will "),n("em",[e._v("not")]),e._v(" be"),n("br"),e._v("invoked within the test-managed transaction. Consequently, the result of any such actions"),n("br"),e._v("will not be rolled back with the test-managed transaction. On the contrary, such actions"),n("br"),e._v("will be committed to the persistent store — for example, a relational database — even"),n("br"),e._v("though the test-managed transaction is properly rolled back by Spring."),n("br"),n("br"),e._v("Situations in which this can occur include but are not limited to the following."),n("br"),n("br"),e._v("* JUnit 4’s "),n("code",[e._v("@Test(timeout = …​)")]),e._v(" support and "),n("code",[e._v("TimeOut")]),e._v(" rule"),n("br"),n("br"),e._v("* JUnit Jupiter’s "),n("code",[e._v("assertTimeoutPreemptively(…​)")]),e._v(" methods in the"),n("code",[e._v("org.junit.jupiter.api.Assertions")]),e._v(" class"),n("br"),n("br"),e._v("* TestNG’s "),n("code",[e._v("@Test(timeOut = …​)")]),e._v(" support")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"enabling-and-disabling-transactions"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#enabling-and-disabling-transactions"}},[e._v("#")]),e._v(" Enabling and Disabling Transactions")]),e._v(" "),n("p",[e._v("Annotating a test method with "),n("code",[e._v("@Transactional")]),e._v(" causes the test to be run within a\ntransaction that is, by default, automatically rolled back after completion of the test.\nIf a test class is annotated with "),n("code",[e._v("@Transactional")]),e._v(", each test method within that class\nhierarchy runs within a transaction. Test methods that are not annotated with"),n("code",[e._v("@Transactional")]),e._v(" (at the class or method level) are not run within a transaction. Note\nthat "),n("code",[e._v("@Transactional")]),e._v(" is not supported on test lifecycle methods — for example, methods\nannotated with JUnit Jupiter’s "),n("code",[e._v("@BeforeAll")]),e._v(", "),n("code",[e._v("@BeforeEach")]),e._v(", etc. Furthermore, tests that\nare annotated with "),n("code",[e._v("@Transactional")]),e._v(" but have the "),n("code",[e._v("propagation")]),e._v(" attribute set to"),n("code",[e._v("NOT_SUPPORTED")]),e._v(" or "),n("code",[e._v("NEVER")]),e._v(" are not run within a transaction.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th",[e._v("Attribute")]),e._v(" "),n("th",[e._v("Supported for test-managed transactions")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("code",[e._v("value")]),e._v(" and "),n("code",[e._v("transactionManager")])]),e._v(" "),n("td",[e._v("yes")])]),e._v(" "),n("tr",[n("td",[n("code",[e._v("propagation")])]),e._v(" "),n("td",[e._v("only "),n("code",[e._v("Propagation.NOT_SUPPORTED")]),e._v(" and "),n("code",[e._v("Propagation.NEVER")]),e._v(" are supported")])]),e._v(" "),n("tr",[n("td",[n("code",[e._v("isolation")])]),e._v(" "),n("td",[e._v("no")])]),e._v(" "),n("tr",[n("td",[n("code",[e._v("timeout")])]),e._v(" "),n("td",[e._v("no")])]),e._v(" "),n("tr",[n("td",[n("code",[e._v("readOnly")])]),e._v(" "),n("td",[e._v("no")])]),e._v(" "),n("tr",[n("td",[n("code",[e._v("rollbackFor")]),e._v(" and "),n("code",[e._v("rollbackForClassName")])]),e._v(" "),n("td",[e._v("no: use "),n("code",[e._v("TestTransaction.flagForRollback()")]),e._v(" instead")])]),e._v(" "),n("tr",[n("td",[n("code",[e._v("noRollbackFor")]),e._v(" and "),n("code",[e._v("noRollbackForClassName")])]),e._v(" "),n("td",[e._v("no: use "),n("code",[e._v("TestTransaction.flagForCommit()")]),e._v(" instead")])])])]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Method-level lifecycle methods — for example, methods annotated with JUnit Jupiter’s"),n("code",[e._v("@BeforeEach")]),e._v(" or "),n("code",[e._v("@AfterEach")]),e._v(" — are run within a test-managed transaction. On the other"),n("br"),e._v("hand, suite-level and class-level lifecycle methods — for example, methods annotated with"),n("br"),e._v("JUnit Jupiter’s "),n("code",[e._v("@BeforeAll")]),e._v(" or "),n("code",[e._v("@AfterAll")]),e._v(" and methods annotated with TestNG’s"),n("code",[e._v("@BeforeSuite")]),e._v(", "),n("code",[e._v("@AfterSuite")]),e._v(", "),n("code",[e._v("@BeforeClass")]),e._v(", or "),n("code",[e._v("@AfterClass")]),e._v(" — are "),n("em",[e._v("not")]),e._v(" run within a"),n("br"),e._v("test-managed transaction."),n("br"),n("br"),e._v("If you need to run code in a suite-level or class-level lifecycle method within a"),n("br"),e._v("transaction, you may wish to inject a corresponding "),n("code",[e._v("PlatformTransactionManager")]),e._v(" into"),n("br"),e._v("your test class and then use that with a "),n("code",[e._v("TransactionTemplate")]),e._v(" for programmatic"),n("br"),e._v("transaction management.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Note that "),n("a",{attrs:{href:"#testcontext-support-classes-junit4"}},[n("code",[e._v("AbstractTransactionalJUnit4SpringContextTests")])]),e._v(" and"),n("a",{attrs:{href:"#testcontext-support-classes-testng"}},[n("code",[e._v("AbstractTransactionalTestNGSpringContextTests")])]),e._v("are preconfigured for transactional support at the class level.")]),e._v(" "),n("p",[e._v("The following example demonstrates a common scenario for writing an integration test for\na Hibernate-based "),n("code",[e._v("UserRepository")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(TestConfig.class)\n@Transactional\nclass HibernateUserRepositoryTests {\n\n @Autowired\n HibernateUserRepository repository;\n\n @Autowired\n SessionFactory sessionFactory;\n\n JdbcTemplate jdbcTemplate;\n\n @Autowired\n void setDataSource(DataSource dataSource) {\n this.jdbcTemplate = new JdbcTemplate(dataSource);\n }\n\n @Test\n void createUser() {\n // track initial state in test database:\n final int count = countRowsInTable("user");\n\n User user = new User(...);\n repository.save(user);\n\n // Manual flush is required to avoid false positive in test\n sessionFactory.getCurrentSession().flush();\n assertNumUsers(count + 1);\n }\n\n private int countRowsInTable(String tableName) {\n return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName);\n }\n\n private void assertNumUsers(int expected) {\n assertEquals("Number of rows in the [user] table.", expected, countRowsInTable("user"));\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(TestConfig::class)\n@Transactional\nclass HibernateUserRepositoryTests {\n\n @Autowired\n lateinit var repository: HibernateUserRepository\n\n @Autowired\n lateinit var sessionFactory: SessionFactory\n\n lateinit var jdbcTemplate: JdbcTemplate\n\n @Autowired\n fun setDataSource(dataSource: DataSource) {\n this.jdbcTemplate = JdbcTemplate(dataSource)\n }\n\n @Test\n fun createUser() {\n // track initial state in test database:\n val count = countRowsInTable("user")\n\n val user = User()\n repository.save(user)\n\n // Manual flush is required to avoid false positive in test\n sessionFactory.getCurrentSession().flush()\n assertNumUsers(count + 1)\n }\n\n private fun countRowsInTable(tableName: String): Int {\n return JdbcTestUtils.countRowsInTable(jdbcTemplate, tableName)\n }\n\n private fun assertNumUsers(expected: Int) {\n assertEquals("Number of rows in the [user] table.", expected, countRowsInTable("user"))\n }\n}\n')])])]),n("p",[e._v("As explained in "),n("a",{attrs:{href:"#testcontext-tx-rollback-and-commit-behavior"}},[e._v("Transaction Rollback and Commit Behavior")]),e._v(", there is no need to\nclean up the database after the "),n("code",[e._v("createUser()")]),e._v(" method runs, since any changes made to the\ndatabase are automatically rolled back by the "),n("code",[e._v("TransactionalTestExecutionListener")]),e._v(".")]),e._v(" "),n("h5",{attrs:{id:"transaction-rollback-and-commit-behavior"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#transaction-rollback-and-commit-behavior"}},[e._v("#")]),e._v(" Transaction Rollback and Commit Behavior")]),e._v(" "),n("p",[e._v("By default, test transactions will be automatically rolled back after completion of the\ntest; however, transactional commit and rollback behavior can be configured declaratively\nvia the "),n("code",[e._v("@Commit")]),e._v(" and "),n("code",[e._v("@Rollback")]),e._v(" annotations. See the corresponding entries in the"),n("a",{attrs:{href:"#integration-testing-annotations"}},[e._v("annotation support")]),e._v(" section for further details.")]),e._v(" "),n("h5",{attrs:{id:"programmatic-transaction-management"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#programmatic-transaction-management"}},[e._v("#")]),e._v(" Programmatic Transaction Management")]),e._v(" "),n("p",[e._v("You can interact with test-managed transactions programmatically by using the static\nmethods in "),n("code",[e._v("TestTransaction")]),e._v(". For example, you can use "),n("code",[e._v("TestTransaction")]),e._v(" within test\nmethods, before methods, and after methods to start or end the current test-managed\ntransaction or to configure the current test-managed transaction for rollback or commit.\nSupport for "),n("code",[e._v("TestTransaction")]),e._v(" is automatically available whenever the"),n("code",[e._v("TransactionalTestExecutionListener")]),e._v(" is enabled.")]),e._v(" "),n("p",[e._v("The following example demonstrates some of the features of "),n("code",[e._v("TestTransaction")]),e._v(". See the\njavadoc for "),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/transaction/TestTransaction.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("TestTransaction")]),n("OutboundLink")],1),e._v("for further details.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration(classes = TestConfig.class)\npublic class ProgrammaticTransactionManagementTests extends\n AbstractTransactionalJUnit4SpringContextTests {\n\n @Test\n public void transactionalTest() {\n // assert initial state in test database:\n assertNumUsers(2);\n\n deleteFromTables("user");\n\n // changes to the database will be committed!\n TestTransaction.flagForCommit();\n TestTransaction.end();\n assertFalse(TestTransaction.isActive());\n assertNumUsers(0);\n\n TestTransaction.start();\n // perform other actions against the database that will\n // be automatically rolled back after the test completes...\n }\n\n protected void assertNumUsers(int expected) {\n assertEquals("Number of rows in the [user] table.", expected, countRowsInTable("user"));\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ContextConfiguration(classes = [TestConfig::class])\nclass ProgrammaticTransactionManagementTests : AbstractTransactionalJUnit4SpringContextTests() {\n\n @Test\n fun transactionalTest() {\n // assert initial state in test database:\n assertNumUsers(2)\n\n deleteFromTables("user")\n\n // changes to the database will be committed!\n TestTransaction.flagForCommit()\n TestTransaction.end()\n assertFalse(TestTransaction.isActive())\n assertNumUsers(0)\n\n TestTransaction.start()\n // perform other actions against the database that will\n // be automatically rolled back after the test completes...\n }\n\n protected fun assertNumUsers(expected: Int) {\n assertEquals("Number of rows in the [user] table.", expected, countRowsInTable("user"))\n }\n}\n')])])]),n("h5",{attrs:{id:"running-code-outside-of-a-transaction"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#running-code-outside-of-a-transaction"}},[e._v("#")]),e._v(" Running Code Outside of a Transaction")]),e._v(" "),n("p",[e._v("Occasionally, you may need to run certain code before or after a transactional test\nmethod but outside the transactional context — for example, to verify the initial\ndatabase state prior to running your test or to verify expected transactional commit\nbehavior after your test runs (if the test was configured to commit the transaction)."),n("code",[e._v("TransactionalTestExecutionListener")]),e._v(" supports the "),n("code",[e._v("@BeforeTransaction")]),e._v(" and"),n("code",[e._v("@AfterTransaction")]),e._v(" annotations for exactly such scenarios. You can annotate any "),n("code",[e._v("void")]),e._v("method in a test class or any "),n("code",[e._v("void")]),e._v(" default method in a test interface with one of these\nannotations, and the "),n("code",[e._v("TransactionalTestExecutionListener")]),e._v(" ensures that your before\ntransaction method or after transaction method runs at the appropriate time.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Any before methods (such as methods annotated with JUnit Jupiter’s "),n("code",[e._v("@BeforeEach")]),e._v(")"),n("br"),e._v("and any after methods (such as methods annotated with JUnit Jupiter’s "),n("code",[e._v("@AfterEach")]),e._v(") are"),n("br"),e._v("run within a transaction. In addition, methods annotated with "),n("code",[e._v("@BeforeTransaction")]),e._v(" or"),n("code",[e._v("@AfterTransaction")]),e._v(" are not run for test methods that are not configured to run within a"),n("br"),e._v("transaction.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"configuring-a-transaction-manager"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#configuring-a-transaction-manager"}},[e._v("#")]),e._v(" Configuring a Transaction Manager")]),e._v(" "),n("p",[n("code",[e._v("TransactionalTestExecutionListener")]),e._v(" expects a "),n("code",[e._v("PlatformTransactionManager")]),e._v(" bean to be\ndefined in the Spring "),n("code",[e._v("ApplicationContext")]),e._v(" for the test. If there are multiple instances\nof "),n("code",[e._v("PlatformTransactionManager")]),e._v(" within the test’s "),n("code",[e._v("ApplicationContext")]),e._v(", you can declare a\nqualifier by using "),n("code",[e._v('@Transactional("myTxMgr")')]),e._v(" or "),n("code",[e._v('@Transactional(transactionManager = "myTxMgr")')]),e._v(", or "),n("code",[e._v("TransactionManagementConfigurer")]),e._v(" can be implemented by an"),n("code",[e._v("@Configuration")]),e._v(" class. Consult the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/transaction/TestContextTransactionUtils.html#retrieveTransactionManager-org.springframework.test.context.TestContext-java.lang.String-",target:"_blank",rel:"noopener noreferrer"}},[e._v("javadoc\nfor "),n("code",[e._v("TestContextTransactionUtils.retrieveTransactionManager()")]),n("OutboundLink")],1),e._v(" for details on the\nalgorithm used to look up a transaction manager in the test’s "),n("code",[e._v("ApplicationContext")]),e._v(".")]),e._v(" "),n("h5",{attrs:{id:"demonstration-of-all-transaction-related-annotations"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#demonstration-of-all-transaction-related-annotations"}},[e._v("#")]),e._v(" Demonstration of All Transaction-related Annotations")]),e._v(" "),n("p",[e._v("The following JUnit Jupiter based example displays a fictitious integration testing\nscenario that highlights all transaction-related annotations. The example is not intended\nto demonstrate best practices but rather to demonstrate how these annotations can be\nused. See the "),n("a",{attrs:{href:"#integration-testing-annotations"}},[e._v("annotation support")]),e._v(" section for further\ninformation and configuration examples. "),n("a",{attrs:{href:"#testcontext-executing-sql-declaratively-tx"}},[e._v("Transaction management for "),n("code",[e._v("@Sql")])]),e._v(" contains an additional example that uses "),n("code",[e._v("@Sql")]),e._v(" for\ndeclarative SQL script execution with default transaction rollback semantics. The\nfollowing example shows the relevant annotations:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig\n@Transactional(transactionManager = "txMgr")\n@Commit\nclass FictitiousTransactionalTest {\n\n @BeforeTransaction\n void verifyInitialDatabaseState() {\n // logic to verify the initial state before a transaction is started\n }\n\n @BeforeEach\n void setUpTestDataWithinTransaction() {\n // set up test data within the transaction\n }\n\n @Test\n // overrides the class-level @Commit setting\n @Rollback\n void modifyDatabaseWithinTransaction() {\n // logic which uses the test data and modifies database state\n }\n\n @AfterEach\n void tearDownWithinTransaction() {\n // run "tear down" logic within the transaction\n }\n\n @AfterTransaction\n void verifyFinalDatabaseState() {\n // logic to verify the final state after transaction has rolled back\n }\n\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig\n@Transactional(transactionManager = "txMgr")\n@Commit\nclass FictitiousTransactionalTest {\n\n @BeforeTransaction\n fun verifyInitialDatabaseState() {\n // logic to verify the initial state before a transaction is started\n }\n\n @BeforeEach\n fun setUpTestDataWithinTransaction() {\n // set up test data within the transaction\n }\n\n @Test\n // overrides the class-level @Commit setting\n @Rollback\n fun modifyDatabaseWithinTransaction() {\n // logic which uses the test data and modifies database state\n }\n\n @AfterEach\n fun tearDownWithinTransaction() {\n // run "tear down" logic within the transaction\n }\n\n @AfterTransaction\n fun verifyFinalDatabaseState() {\n // logic to verify the final state after transaction has rolled back\n }\n\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Avoid false positives when testing ORM code"),n("br"),n("br"),e._v("When you test application code that manipulates the state of a Hibernate session or JPA"),n("br"),e._v("persistence context, make sure to flush the underlying unit of work within test methods"),n("br"),e._v("that run that code. Failing to flush the underlying unit of work can produce false"),n("br"),e._v("positives: Your test passes, but the same code throws an exception in a live, production"),n("br"),e._v("environment. Note that this applies to any ORM framework that maintains an in-memory unit"),n("br"),e._v("of work. In the following Hibernate-based example test case, one method demonstrates a"),n("br"),e._v("false positive, and the other method correctly exposes the results of flushing the"),n("br"),e._v("session:"),n("br"),n("br"),e._v("Java"),n("br"),n("br"),n("code",[e._v("
// ...

@Autowired
SessionFactory sessionFactory;

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

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

// ...
")]),n("br"),n("br"),e._v("Kotlin"),n("br"),n("br"),n("code",[e._v("
// ...

@Autowired
lateinit var sessionFactory: SessionFactory

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

@Transactional
@Test(expected = ...)
fun updateWithSessionFlush() {
updateEntityInHibernateSession()
// Manual flush is required to avoid false positive in test
sessionFactory.getCurrentSession().flush()
}

// ...
")]),n("br"),n("br"),e._v("The following example shows matching methods for JPA:"),n("br"),n("br"),e._v("Java"),n("br"),n("br"),n("code",[e._v("
// ...

@PersistenceContext
EntityManager entityManager;

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

@Transactional
@Test(expected = ...)
public void updateWithEntityManagerFlush() {
updateEntityInJpaPersistenceContext();
// Manual flush is required to avoid false positive in test
entityManager.flush();
}

// ...
")]),n("br"),n("br"),e._v("Kotlin"),n("br"),n("br"),n("code",[e._v("
// ...

@PersistenceContext
lateinit var entityManager:EntityManager

@Transactional
@Test // no expected exception!
fun falsePositive() {
updateEntityInJpaPersistenceContext()
// False positive: an exception will be thrown once the JPA
// EntityManager is finally flushed (i.e., in production code)
}

@Transactional
@Test(expected = ...)
void updateWithEntityManagerFlush() {
updateEntityInJpaPersistenceContext()
// Manual flush is required to avoid false positive in test
entityManager.flush()
}

// ...
")])])])]),e._v(" "),n("tbody")]),e._v(" "),n("h4",{attrs:{id:"_3-5-10-executing-sql-scripts"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-10-executing-sql-scripts"}},[e._v("#")]),e._v(" 3.5.10. Executing SQL Scripts")]),e._v(" "),n("p",[e._v("When writing integration tests against a relational database, it is often beneficial to\nrun SQL scripts to modify the database schema or insert test data into tables. The"),n("code",[e._v("spring-jdbc")]),e._v(" module provides support for "),n("em",[e._v("initializing")]),e._v(" an embedded or existing database\nby executing SQL scripts when the Spring "),n("code",[e._v("ApplicationContext")]),e._v(" is loaded. See"),n("RouterLink",{attrs:{to:"/en/spring-framework/data-access.html#jdbc-embedded-database-support"}},[e._v("Embedded database support")]),e._v(" and"),n("RouterLink",{attrs:{to:"/en/spring-framework/data-access.html#jdbc-embedded-database-dao-testing"}},[e._v("Testing data access logic with an\nembedded database")]),e._v(" for details.")],1),e._v(" "),n("p",[e._v("Although it is very useful to initialize a database for testing "),n("em",[e._v("once")]),e._v(" when the"),n("code",[e._v("ApplicationContext")]),e._v(" is loaded, sometimes it is essential to be able to modify the\ndatabase "),n("em",[e._v("during")]),e._v(" integration tests. The following sections explain how to run SQL\nscripts programmatically and declaratively during integration tests.")]),e._v(" "),n("h5",{attrs:{id:"executing-sql-scripts-programmatically"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#executing-sql-scripts-programmatically"}},[e._v("#")]),e._v(" Executing SQL scripts programmatically")]),e._v(" "),n("p",[e._v("Spring provides the following options for executing SQL scripts programmatically within\nintegration test methods.")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("org.springframework.jdbc.datasource.init.ScriptUtils")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("org.springframework.jdbc.datasource.init.ResourceDatabasePopulator")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests")])])])]),e._v(" "),n("p",[n("code",[e._v("ScriptUtils")]),e._v(" provides a collection of static utility methods for working with SQL\nscripts and is mainly intended for internal use within the framework. However, if you\nrequire full control over how SQL scripts are parsed and run, "),n("code",[e._v("ScriptUtils")]),e._v(" may suit\nyour needs better than some of the other alternatives described later. See the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/jdbc/datasource/init/ScriptUtils.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("javadoc"),n("OutboundLink")],1),e._v(" for individual\nmethods in "),n("code",[e._v("ScriptUtils")]),e._v(" for further details.")]),e._v(" "),n("p",[n("code",[e._v("ResourceDatabasePopulator")]),e._v(" provides an object-based API for programmatically populating,\ninitializing, or cleaning up a database by using SQL scripts defined in external\nresources. "),n("code",[e._v("ResourceDatabasePopulator")]),e._v(" provides options for configuring the character\nencoding, statement separator, comment delimiters, and error handling flags used when\nparsing and running the scripts. Each of the configuration options has a reasonable\ndefault value. See the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("javadoc"),n("OutboundLink")],1),e._v(" for\ndetails on default values. To run the scripts configured in a"),n("code",[e._v("ResourceDatabasePopulator")]),e._v(", you can invoke either the "),n("code",[e._v("populate(Connection)")]),e._v(" method to\nrun the populator against a "),n("code",[e._v("java.sql.Connection")]),e._v(" or the "),n("code",[e._v("execute(DataSource)")]),e._v(" method\nto run the populator against a "),n("code",[e._v("javax.sql.DataSource")]),e._v(". The following example\nspecifies SQL scripts for a test schema and test data, sets the statement separator to"),n("code",[e._v("@@")]),e._v(", and run the scripts against a "),n("code",[e._v("DataSource")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\nvoid databaseTest() {\n ResourceDatabasePopulator populator = new ResourceDatabasePopulator();\n populator.addScripts(\n new ClassPathResource("test-schema.sql"),\n new ClassPathResource("test-data.sql"));\n populator.setSeparator("@@");\n populator.execute(this.dataSource);\n // run code that uses the test schema and data\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\nfun databaseTest() {\n val populator = ResourceDatabasePopulator()\n populator.addScripts(\n ClassPathResource("test-schema.sql"),\n ClassPathResource("test-data.sql"))\n populator.setSeparator("@@")\n populator.execute(dataSource)\n // run code that uses the test schema and data\n}\n')])])]),n("p",[e._v("Note that "),n("code",[e._v("ResourceDatabasePopulator")]),e._v(" internally delegates to "),n("code",[e._v("ScriptUtils")]),e._v(" for parsing\nand running SQL scripts. Similarly, the "),n("code",[e._v("executeSqlScript(..)")]),e._v(" methods in"),n("a",{attrs:{href:"#testcontext-support-classes-junit4"}},[n("code",[e._v("AbstractTransactionalJUnit4SpringContextTests")])]),e._v("and "),n("a",{attrs:{href:"#testcontext-support-classes-testng"}},[n("code",[e._v("AbstractTransactionalTestNGSpringContextTests")])]),e._v("internally use a "),n("code",[e._v("ResourceDatabasePopulator")]),e._v(" to run SQL scripts. See the Javadoc for the\nvarious "),n("code",[e._v("executeSqlScript(..)")]),e._v(" methods for further details.")]),e._v(" "),n("h5",{attrs:{id:"executing-sql-scripts-declaratively-with-sql"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#executing-sql-scripts-declaratively-with-sql"}},[e._v("#")]),e._v(" Executing SQL scripts declaratively with @Sql")]),e._v(" "),n("p",[e._v("In addition to the aforementioned mechanisms for running SQL scripts programmatically,\nyou can declaratively configure SQL scripts in the Spring TestContext Framework.\nSpecifically, you can declare the "),n("code",[e._v("@Sql")]),e._v(" annotation on a test class or test method to\nconfigure individual SQL statements or the resource paths to SQL scripts that should be\nrun against a given database before or after an integration test method. Support for"),n("code",[e._v("@Sql")]),e._v(" is provided by the "),n("code",[e._v("SqlScriptsTestExecutionListener")]),e._v(", which is enabled by default.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Method-level "),n("code",[e._v("@Sql")]),e._v(" declarations override class-level declarations by default. As"),n("br"),e._v("of Spring Framework 5.2, however, this behavior may be configured per test class or per"),n("br"),e._v("test method via "),n("code",[e._v("@SqlMergeMode")]),e._v(". See"),n("a",{attrs:{href:"#testcontext-executing-sql-declaratively-script-merging"}},[e._v("Merging and Overriding Configuration with "),n("code",[e._v("@SqlMergeMode")])]),e._v(" for further details.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h6",{attrs:{id:"path-resource-semantics"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#path-resource-semantics"}},[e._v("#")]),e._v(" Path Resource Semantics")]),e._v(" "),n("p",[e._v("Each path is interpreted as a Spring "),n("code",[e._v("Resource")]),e._v(". A plain path (for example,"),n("code",[e._v('"schema.sql"')]),e._v(") is treated as a classpath resource that is relative to the package in\nwhich the test class is defined. A path starting with a slash is treated as an absolute\nclasspath resource (for example, "),n("code",[e._v('"/org/example/schema.sql"')]),e._v("). A path that references a\nURL (for example, a path prefixed with "),n("code",[e._v("classpath:")]),e._v(", "),n("code",[e._v("file:")]),e._v(", "),n("code",[e._v("http:")]),e._v(") is loaded by using\nthe specified resource protocol.")]),e._v(" "),n("p",[e._v("The following example shows how to use "),n("code",[e._v("@Sql")]),e._v(" at the class level and at the method level\nwithin a JUnit Jupiter based integration test class:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig\n@Sql("/test-schema.sql")\nclass DatabaseTests {\n\n @Test\n void emptySchemaTest() {\n // run code that uses the test schema without any test data\n }\n\n @Test\n @Sql({"/test-schema.sql", "/test-user-data.sql"})\n void userTest() {\n // run code that uses the test schema and test data\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig\n@Sql("/test-schema.sql")\nclass DatabaseTests {\n\n @Test\n fun emptySchemaTest() {\n // run code that uses the test schema without any test data\n }\n\n @Test\n @Sql("/test-schema.sql", "/test-user-data.sql")\n fun userTest() {\n // run code that uses the test schema and test data\n }\n}\n')])])]),n("h6",{attrs:{id:"default-script-detection"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#default-script-detection"}},[e._v("#")]),e._v(" Default Script Detection")]),e._v(" "),n("p",[e._v("If no SQL scripts or statements are specified, an attempt is made to detect a "),n("code",[e._v("default")]),e._v("script, depending on where "),n("code",[e._v("@Sql")]),e._v(" is declared. If a default cannot be detected, an"),n("code",[e._v("IllegalStateException")]),e._v(" is thrown.")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("Class-level declaration: If the annotated test class is "),n("code",[e._v("com.example.MyTest")]),e._v(", the\ncorresponding default script is "),n("code",[e._v("classpath:com/example/MyTest.sql")]),e._v(".")])]),e._v(" "),n("li",[n("p",[e._v("Method-level declaration: If the annotated test method is named "),n("code",[e._v("testMethod()")]),e._v(" and is\ndefined in the class "),n("code",[e._v("com.example.MyTest")]),e._v(", the corresponding default script is"),n("code",[e._v("classpath:com/example/MyTest.testMethod.sql")]),e._v(".")])])]),e._v(" "),n("h6",{attrs:{id:"declaring-multiple-sql-sets"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#declaring-multiple-sql-sets"}},[e._v("#")]),e._v(" Declaring Multiple "),n("code",[e._v("@Sql")]),e._v(" Sets")]),e._v(" "),n("p",[e._v("If you need to configure multiple sets of SQL scripts for a given test class or test\nmethod but with different syntax configuration, different error handling rules, or\ndifferent execution phases per set, you can declare multiple instances of "),n("code",[e._v("@Sql")]),e._v(". With\nJava 8, you can use "),n("code",[e._v("@Sql")]),e._v(" as a repeatable annotation. Otherwise, you can use the"),n("code",[e._v("@SqlGroup")]),e._v(" annotation as an explicit container for declaring multiple instances of"),n("code",[e._v("@Sql")]),e._v(".")]),e._v(" "),n("p",[e._v("The following example shows how to use "),n("code",[e._v("@Sql")]),e._v(" as a repeatable annotation with Java 8:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\n@Sql(scripts = "/test-schema.sql", config = @SqlConfig(commentPrefix = "`"))\n@Sql("/test-user-data.sql")\nvoid userTest() {\n // run code that uses the test schema and test data\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Repeatable annotations with non-SOURCE retention are not yet supported by Kotlin\n")])])]),n("p",[e._v("In the scenario presented in the preceding example, the "),n("code",[e._v("test-schema.sql")]),e._v(" script uses a\ndifferent syntax for single-line comments.")]),e._v(" "),n("p",[e._v("The following example is identical to the preceding example, except that the "),n("code",[e._v("@Sql")]),e._v("declarations are grouped together within "),n("code",[e._v("@SqlGroup")]),e._v(". With Java 8 and above, the use of"),n("code",[e._v("@SqlGroup")]),e._v(" is optional, but you may need to use "),n("code",[e._v("@SqlGroup")]),e._v(" for compatibility with\nother JVM languages such as Kotlin.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\n@SqlGroup({\n @Sql(scripts = "/test-schema.sql", config = @SqlConfig(commentPrefix = "`")),\n @Sql("/test-user-data.sql")\n)}\nvoid userTest() {\n // run code that uses the test schema and test data\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\n@SqlGroup(\n Sql("/test-schema.sql", config = SqlConfig(commentPrefix = "`")),\n Sql("/test-user-data.sql"))\nfun userTest() {\n // Run code that uses the test schema and test data\n}\n')])])]),n("h6",{attrs:{id:"script-execution-phases"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#script-execution-phases"}},[e._v("#")]),e._v(" Script Execution Phases")]),e._v(" "),n("p",[e._v("By default, SQL scripts are run before the corresponding test method. However, if\nyou need to run a particular set of scripts after the test method (for example, to clean\nup database state), you can use the "),n("code",[e._v("executionPhase")]),e._v(" attribute in "),n("code",[e._v("@Sql")]),e._v(", as the\nfollowing example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\n@Sql(\n scripts = "create-test-data.sql",\n config = @SqlConfig(transactionMode = ISOLATED)\n)\n@Sql(\n scripts = "delete-test-data.sql",\n config = @SqlConfig(transactionMode = ISOLATED),\n executionPhase = AFTER_TEST_METHOD\n)\nvoid userTest() {\n // run code that needs the test data to be committed\n // to the database outside of the test\'s transaction\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\n@SqlGroup(\n Sql("create-test-data.sql",\n config = SqlConfig(transactionMode = ISOLATED)),\n Sql("delete-test-data.sql",\n config = SqlConfig(transactionMode = ISOLATED),\n executionPhase = AFTER_TEST_METHOD))\nfun userTest() {\n // run code that needs the test data to be committed\n // to the database outside of the test\'s transaction\n}\n')])])]),n("p",[e._v("Note that "),n("code",[e._v("ISOLATED")]),e._v(" and "),n("code",[e._v("AFTER_TEST_METHOD")]),e._v(" are statically imported from"),n("code",[e._v("Sql.TransactionMode")]),e._v(" and "),n("code",[e._v("Sql.ExecutionPhase")]),e._v(", respectively.")]),e._v(" "),n("h6",{attrs:{id:"script-configuration-with-sqlconfig"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#script-configuration-with-sqlconfig"}},[e._v("#")]),e._v(" Script Configuration with "),n("code",[e._v("@SqlConfig")])]),e._v(" "),n("p",[e._v("You can configure script parsing and error handling by using the "),n("code",[e._v("@SqlConfig")]),e._v(" annotation.\nWhen declared as a class-level annotation on an integration test class, "),n("code",[e._v("@SqlConfig")]),e._v("serves as global configuration for all SQL scripts within the test class hierarchy. When\ndeclared directly by using the "),n("code",[e._v("config")]),e._v(" attribute of the "),n("code",[e._v("@Sql")]),e._v(" annotation, "),n("code",[e._v("@SqlConfig")]),e._v("serves as local configuration for the SQL scripts declared within the enclosing "),n("code",[e._v("@Sql")]),e._v("annotation. Every attribute in "),n("code",[e._v("@SqlConfig")]),e._v(" has an implicit default value, which is\ndocumented in the javadoc of the corresponding attribute. Due to the rules defined for\nannotation attributes in the Java Language Specification, it is, unfortunately, not\npossible to assign a value of "),n("code",[e._v("null")]),e._v(" to an annotation attribute. Thus, in order to\nsupport overrides of inherited global configuration, "),n("code",[e._v("@SqlConfig")]),e._v(" attributes have an\nexplicit default value of either "),n("code",[e._v('""')]),e._v(" (for Strings), "),n("code",[e._v("{}")]),e._v(" (for arrays), or "),n("code",[e._v("DEFAULT")]),e._v(" (for\nenumerations). This approach lets local declarations of "),n("code",[e._v("@SqlConfig")]),e._v(" selectively override\nindividual attributes from global declarations of "),n("code",[e._v("@SqlConfig")]),e._v(" by providing a value other\nthan "),n("code",[e._v('""')]),e._v(", "),n("code",[e._v("{}")]),e._v(", or "),n("code",[e._v("DEFAULT")]),e._v(". Global "),n("code",[e._v("@SqlConfig")]),e._v(" attributes are inherited whenever\nlocal "),n("code",[e._v("@SqlConfig")]),e._v(" attributes do not supply an explicit value other than "),n("code",[e._v('""')]),e._v(", "),n("code",[e._v("{}")]),e._v(", or"),n("code",[e._v("DEFAULT")]),e._v(". Explicit local configuration, therefore, overrides global configuration.")]),e._v(" "),n("p",[e._v("The configuration options provided by "),n("code",[e._v("@Sql")]),e._v(" and "),n("code",[e._v("@SqlConfig")]),e._v(" are equivalent to those\nsupported by "),n("code",[e._v("ScriptUtils")]),e._v(" and "),n("code",[e._v("ResourceDatabasePopulator")]),e._v(" but are a superset of those\nprovided by the "),n("code",[e._v("")]),e._v(" XML namespace element. See the javadoc of\nindividual attributes in "),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/jdbc/Sql.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@Sql")]),n("OutboundLink")],1),e._v(" and"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/jdbc/SqlConfig.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@SqlConfig")]),n("OutboundLink")],1),e._v(" for details.")]),e._v(" "),n("p",[n("strong",[e._v("Transaction management for "),n("code",[e._v("@Sql")])])]),e._v(" "),n("p",[e._v("By default, the "),n("code",[e._v("SqlScriptsTestExecutionListener")]),e._v(" infers the desired transaction\nsemantics for scripts configured by using "),n("code",[e._v("@Sql")]),e._v(". Specifically, SQL scripts are run\nwithout a transaction, within an existing Spring-managed transaction (for example, a\ntransaction managed by the "),n("code",[e._v("TransactionalTestExecutionListener")]),e._v(" for a test annotated with"),n("code",[e._v("@Transactional")]),e._v("), or within an isolated transaction, depending on the configured value\nof the "),n("code",[e._v("transactionMode")]),e._v(" attribute in "),n("code",[e._v("@SqlConfig")]),e._v(" and the presence of a"),n("code",[e._v("PlatformTransactionManager")]),e._v(" in the test’s "),n("code",[e._v("ApplicationContext")]),e._v(". As a bare minimum,\nhowever, a "),n("code",[e._v("javax.sql.DataSource")]),e._v(" must be present in the test’s "),n("code",[e._v("ApplicationContext")]),e._v(".")]),e._v(" "),n("p",[e._v("If the algorithms used by "),n("code",[e._v("SqlScriptsTestExecutionListener")]),e._v(" to detect a "),n("code",[e._v("DataSource")]),e._v(" and"),n("code",[e._v("PlatformTransactionManager")]),e._v(" and infer the transaction semantics do not suit your needs,\nyou can specify explicit names by setting the "),n("code",[e._v("dataSource")]),e._v(" and "),n("code",[e._v("transactionManager")]),e._v("attributes of "),n("code",[e._v("@SqlConfig")]),e._v(". Furthermore, you can control the transaction propagation\nbehavior by setting the "),n("code",[e._v("transactionMode")]),e._v(" attribute of "),n("code",[e._v("@SqlConfig")]),e._v(" (for example, whether\nscripts should be run in an isolated transaction). Although a thorough discussion of all\nsupported options for transaction management with "),n("code",[e._v("@Sql")]),e._v(" is beyond the scope of this\nreference manual, the javadoc for"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/jdbc/SqlConfig.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@SqlConfig")]),n("OutboundLink")],1),e._v(" and"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/jdbc/SqlScriptsTestExecutionListener.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("SqlScriptsTestExecutionListener")]),n("OutboundLink")],1),e._v("provide detailed information, and the following example shows a typical testing scenario\nthat uses JUnit Jupiter and transactional tests with "),n("code",[e._v("@Sql")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(TestDatabaseConfig.class)\n@Transactional\nclass TransactionalSqlScriptsTests {\n\n final JdbcTemplate jdbcTemplate;\n\n @Autowired\n TransactionalSqlScriptsTests(DataSource dataSource) {\n this.jdbcTemplate = new JdbcTemplate(dataSource);\n }\n\n @Test\n @Sql("/test-data.sql")\n void usersTest() {\n // verify state in test database:\n assertNumUsers(2);\n // run code that uses the test data...\n }\n\n int countRowsInTable(String tableName) {\n return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName);\n }\n\n void assertNumUsers(int expected) {\n assertEquals(expected, countRowsInTable("user"),\n "Number of rows in the [user] table.");\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(TestDatabaseConfig::class)\n@Transactional\nclass TransactionalSqlScriptsTests @Autowired constructor(dataSource: DataSource) {\n\n val jdbcTemplate: JdbcTemplate = JdbcTemplate(dataSource)\n\n @Test\n @Sql("/test-data.sql")\n fun usersTest() {\n // verify state in test database:\n assertNumUsers(2)\n // run code that uses the test data...\n }\n\n fun countRowsInTable(tableName: String): Int {\n return JdbcTestUtils.countRowsInTable(jdbcTemplate, tableName)\n }\n\n fun assertNumUsers(expected: Int) {\n assertEquals(expected, countRowsInTable("user"),\n "Number of rows in the [user] table.")\n }\n}\n')])])]),n("p",[e._v("Note that there is no need to clean up the database after the "),n("code",[e._v("usersTest()")]),e._v(" method is\nrun, since any changes made to the database (either within the test method or within the"),n("code",[e._v("/test-data.sql")]),e._v(" script) are automatically rolled back by the"),n("code",[e._v("TransactionalTestExecutionListener")]),e._v(" (see "),n("a",{attrs:{href:"#testcontext-tx"}},[e._v("transaction management")]),e._v(" for\ndetails).")]),e._v(" "),n("h6",{attrs:{id:"merging-and-overriding-configuration-with-sqlmergemode"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#merging-and-overriding-configuration-with-sqlmergemode"}},[e._v("#")]),e._v(" Merging and Overriding Configuration with "),n("code",[e._v("@SqlMergeMode")])]),e._v(" "),n("p",[e._v("As of Spring Framework 5.2, it is possible to merge method-level "),n("code",[e._v("@Sql")]),e._v(" declarations with\nclass-level declarations. For example, this allows you to provide the configuration for a\ndatabase schema or some common test data once per test class and then provide additional,\nuse case specific test data per test method. To enable "),n("code",[e._v("@Sql")]),e._v(" merging, annotate either\nyour test class or test method with "),n("code",[e._v("@SqlMergeMode(MERGE)")]),e._v(". To disable merging for a\nspecific test method (or specific test subclass), you can switch back to the default mode\nvia "),n("code",[e._v("@SqlMergeMode(OVERRIDE)")]),e._v(". Consult the "),n("a",{attrs:{href:"#spring-testing-annotation-sqlmergemode"}},[n("code",[e._v("@SqlMergeMode")]),e._v(" annotation documentation section")]),e._v(" for examples and further details.")]),e._v(" "),n("h4",{attrs:{id:"_3-5-11-parallel-test-execution"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-11-parallel-test-execution"}},[e._v("#")]),e._v(" 3.5.11. Parallel Test Execution")]),e._v(" "),n("p",[e._v("Spring Framework 5.0 introduced basic support for executing tests in parallel within a\nsingle JVM when using the Spring TestContext Framework. In general, this means that most\ntest classes or test methods can be run in parallel without any changes to test code\nor configuration.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("For details on how to set up parallel test execution, see the documentation for your"),n("br"),e._v("testing framework, build tool, or IDE.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Keep in mind that the introduction of concurrency into your test suite can result in\nunexpected side effects, strange runtime behavior, and tests that fail intermittently or\nseemingly randomly. The Spring Team therefore provides the following general guidelines\nfor when not to run tests in parallel.")]),e._v(" "),n("p",[e._v("Do not run tests in parallel if the tests:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("Use Spring Framework’s "),n("code",[e._v("@DirtiesContext")]),e._v(" support.")])]),e._v(" "),n("li",[n("p",[e._v("Use Spring Boot’s "),n("code",[e._v("@MockBean")]),e._v(" or "),n("code",[e._v("@SpyBean")]),e._v(" support.")])]),e._v(" "),n("li",[n("p",[e._v("Use JUnit 4’s "),n("code",[e._v("@FixMethodOrder")]),e._v(" support or any testing framework feature\nthat is designed to ensure that test methods run in a particular order. Note,\nhowever, that this does not apply if entire test classes are run in parallel.")])]),e._v(" "),n("li",[n("p",[e._v("Change the state of shared services or systems such as a database, message broker,\nfilesystem, and others. This applies to both embedded and external systems.")])])]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("If parallel test execution fails with an exception stating that the "),n("code",[e._v("ApplicationContext")]),e._v("for the current test is no longer active, this typically means that the"),n("code",[e._v("ApplicationContext")]),e._v(" was removed from the "),n("code",[e._v("ContextCache")]),e._v(" in a different thread."),n("br"),n("br"),e._v("This may be due to the use of "),n("code",[e._v("@DirtiesContext")]),e._v(" or due to automatic eviction from the"),n("code",[e._v("ContextCache")]),e._v(". If "),n("code",[e._v("@DirtiesContext")]),e._v(" is the culprit, you either need to find a way to"),n("br"),e._v("avoid using "),n("code",[e._v("@DirtiesContext")]),e._v(" or exclude such tests from parallel execution. If the"),n("br"),e._v("maximum size of the "),n("code",[e._v("ContextCache")]),e._v(" has been exceeded, you can increase the maximum size"),n("br"),e._v("of the cache. See the discussion on "),n("a",{attrs:{href:"#testcontext-ctx-management-caching"}},[e._v("context caching")]),e._v("for details.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Parallel test execution in the Spring TestContext Framework is only possible if"),n("br"),e._v("the underlying "),n("code",[e._v("TestContext")]),e._v(" implementation provides a copy constructor, as explained in"),n("br"),e._v("the javadoc for "),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/context/TestContext.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("TestContext")]),n("OutboundLink")],1),e._v(". The"),n("code",[e._v("DefaultTestContext")]),e._v(" used in Spring provides such a constructor. However, if you use a"),n("br"),e._v("third-party library that provides a custom "),n("code",[e._v("TestContext")]),e._v(" implementation, you need to"),n("br"),e._v("verify that it is suitable for parallel test execution.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h4",{attrs:{id:"_3-5-12-testcontext-framework-support-classes"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-12-testcontext-framework-support-classes"}},[e._v("#")]),e._v(" 3.5.12. TestContext Framework Support Classes")]),e._v(" "),n("p",[e._v("This section describes the various classes that support the Spring TestContext Framework.")]),e._v(" "),n("h5",{attrs:{id:"spring-junit-4-runner"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#spring-junit-4-runner"}},[e._v("#")]),e._v(" Spring JUnit 4 Runner")]),e._v(" "),n("p",[e._v("The Spring TestContext Framework offers full integration with JUnit 4 through a custom\nrunner (supported on JUnit 4.12 or higher). By annotating test classes with"),n("code",[e._v("@RunWith(SpringJUnit4ClassRunner.class)")]),e._v(" or the shorter "),n("code",[e._v("@RunWith(SpringRunner.class)")]),e._v("variant, developers can implement standard JUnit 4-based unit and integration tests and\nsimultaneously reap the benefits of the TestContext framework, such as support for\nloading application contexts, dependency injection of test instances, transactional test\nmethod execution, and so on. If you want to use the Spring TestContext Framework with an\nalternative runner (such as JUnit 4’s "),n("code",[e._v("Parameterized")]),e._v(" runner) or third-party runners\n(such as the "),n("code",[e._v("MockitoJUnitRunner")]),e._v("), you can, optionally, use"),n("a",{attrs:{href:"#testcontext-junit4-rules"}},[e._v("Spring’s support for JUnit rules")]),e._v(" instead.")]),e._v(" "),n("p",[e._v("The following code listing shows the minimal requirements for configuring a test class to\nrun with the custom Spring "),n("code",[e._v("Runner")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@RunWith(SpringRunner.class)\n@TestExecutionListeners({})\npublic class SimpleTest {\n\n @Test\n public void testMethod() {\n // test logic...\n }\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@RunWith(SpringRunner::class)\n@TestExecutionListeners\nclass SimpleTest {\n\n @Test\n fun testMethod() {\n // test logic...\n }\n}\n")])])]),n("p",[e._v("In the preceding example, "),n("code",[e._v("@TestExecutionListeners")]),e._v(" is configured with an empty list, to\ndisable the default listeners, which otherwise would require an "),n("code",[e._v("ApplicationContext")]),e._v(" to\nbe configured through "),n("code",[e._v("@ContextConfiguration")]),e._v(".")]),e._v(" "),n("h5",{attrs:{id:"spring-junit-4-rules"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#spring-junit-4-rules"}},[e._v("#")]),e._v(" Spring JUnit 4 Rules")]),e._v(" "),n("p",[e._v("The "),n("code",[e._v("org.springframework.test.context.junit4.rules")]),e._v(" package provides the following JUnit\n4 rules (supported on JUnit 4.12 or higher):")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("SpringClassRule")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("SpringMethodRule")])])])]),e._v(" "),n("p",[n("code",[e._v("SpringClassRule")]),e._v(" is a JUnit "),n("code",[e._v("TestRule")]),e._v(" that supports class-level features of the Spring\nTestContext Framework, whereas "),n("code",[e._v("SpringMethodRule")]),e._v(" is a JUnit "),n("code",[e._v("MethodRule")]),e._v(" that supports\ninstance-level and method-level features of the Spring TestContext Framework.")]),e._v(" "),n("p",[e._v("In contrast to the "),n("code",[e._v("SpringRunner")]),e._v(", Spring’s rule-based JUnit support has the advantage of\nbeing independent of any "),n("code",[e._v("org.junit.runner.Runner")]),e._v(" implementation and can, therefore, be\ncombined with existing alternative runners (such as JUnit 4’s "),n("code",[e._v("Parameterized")]),e._v(") or\nthird-party runners (such as the "),n("code",[e._v("MockitoJUnitRunner")]),e._v(").")]),e._v(" "),n("p",[e._v("To support the full functionality of the TestContext framework, you must combine a"),n("code",[e._v("SpringClassRule")]),e._v(" with a "),n("code",[e._v("SpringMethodRule")]),e._v(". The following example shows the proper way\nto declare these rules in an integration test:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Optionally specify a non-Spring Runner via @RunWith(...)\n@ContextConfiguration\npublic class IntegrationTest {\n\n @ClassRule\n public static final SpringClassRule springClassRule = new SpringClassRule();\n\n @Rule\n public final SpringMethodRule springMethodRule = new SpringMethodRule();\n\n @Test\n public void testMethod() {\n // test logic...\n }\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Optionally specify a non-Spring Runner via @RunWith(...)\n@ContextConfiguration\nclass IntegrationTest {\n\n @Rule\n val springMethodRule = SpringMethodRule()\n\n @Test\n fun testMethod() {\n // test logic...\n }\n\n companion object {\n @ClassRule\n val springClassRule = SpringClassRule()\n }\n}\n")])])]),n("h5",{attrs:{id:"junit-4-support-classes"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#junit-4-support-classes"}},[e._v("#")]),e._v(" JUnit 4 Support Classes")]),e._v(" "),n("p",[e._v("The "),n("code",[e._v("org.springframework.test.context.junit4")]),e._v(" package provides the following support\nclasses for JUnit 4-based test cases (supported on JUnit 4.12 or higher):")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("AbstractJUnit4SpringContextTests")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("AbstractTransactionalJUnit4SpringContextTests")])])])]),e._v(" "),n("p",[n("code",[e._v("AbstractJUnit4SpringContextTests")]),e._v(" is an abstract base test class that integrates the\nSpring TestContext Framework with explicit "),n("code",[e._v("ApplicationContext")]),e._v(" testing support in a\nJUnit 4 environment. When you extend "),n("code",[e._v("AbstractJUnit4SpringContextTests")]),e._v(", you can access a"),n("code",[e._v("protected")]),e._v(" "),n("code",[e._v("applicationContext")]),e._v(" instance variable that you can use to perform explicit\nbean lookups or to test the state of the context as a whole.")]),e._v(" "),n("p",[n("code",[e._v("AbstractTransactionalJUnit4SpringContextTests")]),e._v(" is an abstract transactional extension of"),n("code",[e._v("AbstractJUnit4SpringContextTests")]),e._v(" that adds some convenience functionality for JDBC\naccess. This class expects a "),n("code",[e._v("javax.sql.DataSource")]),e._v(" bean and a"),n("code",[e._v("PlatformTransactionManager")]),e._v(" bean to be defined in the "),n("code",[e._v("ApplicationContext")]),e._v(". When you\nextend "),n("code",[e._v("AbstractTransactionalJUnit4SpringContextTests")]),e._v(", you can access a "),n("code",[e._v("protected``jdbcTemplate")]),e._v(" instance variable that you can use to run SQL statements to query the\ndatabase. You can use such queries to confirm database state both before and after\nrunning database-related application code, and Spring ensures that such queries run in\nthe scope of the same transaction as the application code. When used in conjunction with\nan ORM tool, be sure to avoid "),n("a",{attrs:{href:"#testcontext-tx-false-positives"}},[e._v("false positives")]),e._v(".\nAs mentioned in "),n("a",{attrs:{href:"#integration-testing-support-jdbc"}},[e._v("JDBC Testing Support")]),e._v(","),n("code",[e._v("AbstractTransactionalJUnit4SpringContextTests")]),e._v(" also provides convenience methods that\ndelegate to methods in "),n("code",[e._v("JdbcTestUtils")]),e._v(" by using the aforementioned "),n("code",[e._v("jdbcTemplate")]),e._v(".\nFurthermore, "),n("code",[e._v("AbstractTransactionalJUnit4SpringContextTests")]),e._v(" provides an"),n("code",[e._v("executeSqlScript(..)")]),e._v(" method for running SQL scripts against the configured "),n("code",[e._v("DataSource")]),e._v(".")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("These classes are a convenience for extension. If you do not want your test classes"),n("br"),e._v("to be tied to a Spring-specific class hierarchy, you can configure your own custom test"),n("br"),e._v("classes by using "),n("code",[e._v("@RunWith(SpringRunner.class)")]),e._v(" or "),n("a",{attrs:{href:"#testcontext-junit4-rules"}},[e._v("Spring’s"),n("br"),e._v("JUnit rules")]),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"springextension-for-junit-jupiter"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#springextension-for-junit-jupiter"}},[e._v("#")]),e._v(" SpringExtension for JUnit Jupiter")]),e._v(" "),n("p",[e._v("The Spring TestContext Framework offers full integration with the JUnit Jupiter testing\nframework, introduced in JUnit 5. By annotating test classes with"),n("code",[e._v("@ExtendWith(SpringExtension.class)")]),e._v(", you can implement standard JUnit Jupiter-based unit\nand integration tests and simultaneously reap the benefits of the TestContext framework,\nsuch as support for loading application contexts, dependency injection of test instances,\ntransactional test method execution, and so on.")]),e._v(" "),n("p",[e._v("Furthermore, thanks to the rich extension API in JUnit Jupiter, Spring provides the\nfollowing features above and beyond the feature set that Spring supports for JUnit 4 and\nTestNG:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("Dependency injection for test constructors, test methods, and test lifecycle callback\nmethods. See "),n("a",{attrs:{href:"#testcontext-junit-jupiter-di"}},[e._v("Dependency Injection with "),n("code",[e._v("SpringExtension")])]),e._v(" for further details.")])]),e._v(" "),n("li",[n("p",[e._v("Powerful support for "),n("a",{attrs:{href:"https://junit.org/junit5/docs/current/user-guide/#extensions-conditions",target:"_blank",rel:"noopener noreferrer"}},[e._v("conditional\ntest execution"),n("OutboundLink")],1),e._v(" based on SpEL expressions, environment variables, system properties,\nand so on. See the documentation for "),n("code",[e._v("@EnabledIf")]),e._v(" and "),n("code",[e._v("@DisabledIf")]),e._v(" in"),n("a",{attrs:{href:"#integration-testing-annotations-junit-jupiter"}},[e._v("Spring JUnit Jupiter Testing Annotations")]),e._v(" for further details and examples.")])]),e._v(" "),n("li",[n("p",[e._v("Custom composed annotations that combine annotations from Spring and JUnit Jupiter. See\nthe "),n("code",[e._v("@TransactionalDevTestConfig")]),e._v(" and "),n("code",[e._v("@TransactionalIntegrationTest")]),e._v(" examples in"),n("a",{attrs:{href:"#integration-testing-annotations-meta"}},[e._v("Meta-Annotation Support for Testing")]),e._v(" for further details.")])])]),e._v(" "),n("p",[e._v("The following code listing shows how to configure a test class to use the"),n("code",[e._v("SpringExtension")]),e._v(" in conjunction with "),n("code",[e._v("@ContextConfiguration")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Instructs JUnit Jupiter to extend the test with Spring support.\n@ExtendWith(SpringExtension.class)\n// Instructs Spring to load an ApplicationContext from TestConfig.class\n@ContextConfiguration(classes = TestConfig.class)\nclass SimpleTests {\n\n @Test\n void testMethod() {\n // test logic...\n }\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Instructs JUnit Jupiter to extend the test with Spring support.\n@ExtendWith(SpringExtension::class)\n// Instructs Spring to load an ApplicationContext from TestConfig::class\n@ContextConfiguration(classes = [TestConfig::class])\nclass SimpleTests {\n\n @Test\n fun testMethod() {\n // test logic...\n }\n}\n")])])]),n("p",[e._v("Since you can also use annotations in JUnit 5 as meta-annotations, Spring provides the"),n("code",[e._v("@SpringJUnitConfig")]),e._v(" and "),n("code",[e._v("@SpringJUnitWebConfig")]),e._v(" composed annotations to simplify the\nconfiguration of the test "),n("code",[e._v("ApplicationContext")]),e._v(" and JUnit Jupiter.")]),e._v(" "),n("p",[e._v("The following example uses "),n("code",[e._v("@SpringJUnitConfig")]),e._v(" to reduce the amount of configuration\nused in the previous example:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Instructs Spring to register the SpringExtension with JUnit\n// Jupiter and load an ApplicationContext from TestConfig.class\n@SpringJUnitConfig(TestConfig.class)\nclass SimpleTests {\n\n @Test\n void testMethod() {\n // test logic...\n }\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Instructs Spring to register the SpringExtension with JUnit\n// Jupiter and load an ApplicationContext from TestConfig.class\n@SpringJUnitConfig(TestConfig::class)\nclass SimpleTests {\n\n @Test\n fun testMethod() {\n // test logic...\n }\n}\n")])])]),n("p",[e._v("Similarly, the following example uses "),n("code",[e._v("@SpringJUnitWebConfig")]),e._v(" to create a"),n("code",[e._v("WebApplicationContext")]),e._v(" for use with JUnit Jupiter:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Instructs Spring to register the SpringExtension with JUnit\n// Jupiter and load a WebApplicationContext from TestWebConfig.class\n@SpringJUnitWebConfig(TestWebConfig.class)\nclass SimpleWebTests {\n\n @Test\n void testMethod() {\n // test logic...\n }\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Instructs Spring to register the SpringExtension with JUnit\n// Jupiter and load a WebApplicationContext from TestWebConfig::class\n@SpringJUnitWebConfig(TestWebConfig::class)\nclass SimpleWebTests {\n\n @Test\n fun testMethod() {\n // test logic...\n }\n}\n")])])]),n("p",[e._v("See the documentation for "),n("code",[e._v("@SpringJUnitConfig")]),e._v(" and "),n("code",[e._v("@SpringJUnitWebConfig")]),e._v(" in"),n("a",{attrs:{href:"#integration-testing-annotations-junit-jupiter"}},[e._v("Spring JUnit Jupiter Testing Annotations")]),e._v(" for further details.")]),e._v(" "),n("h5",{attrs:{id:"dependency-injection-with-springextension"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#dependency-injection-with-springextension"}},[e._v("#")]),e._v(" Dependency Injection with "),n("code",[e._v("SpringExtension")])]),e._v(" "),n("p",[n("code",[e._v("SpringExtension")]),e._v(" implements the"),n("a",{attrs:{href:"https://junit.org/junit5/docs/current/user-guide/#extensions-parameter-resolution",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("ParameterResolver")]),n("OutboundLink")],1),e._v("extension API from JUnit Jupiter, which lets Spring provide dependency injection for test\nconstructors, test methods, and test lifecycle callback methods.")]),e._v(" "),n("p",[e._v("Specifically, "),n("code",[e._v("SpringExtension")]),e._v(" can inject dependencies from the test’s"),n("code",[e._v("ApplicationContext")]),e._v(" into test constructors and methods that are annotated with"),n("code",[e._v("@BeforeAll")]),e._v(", "),n("code",[e._v("@AfterAll")]),e._v(", "),n("code",[e._v("@BeforeEach")]),e._v(", "),n("code",[e._v("@AfterEach")]),e._v(", "),n("code",[e._v("@Test")]),e._v(", "),n("code",[e._v("@RepeatedTest")]),e._v(","),n("code",[e._v("@ParameterizedTest")]),e._v(", and others.")]),e._v(" "),n("h6",{attrs:{id:"constructor-injection"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#constructor-injection"}},[e._v("#")]),e._v(" Constructor Injection")]),e._v(" "),n("p",[e._v("If a specific parameter in a constructor for a JUnit Jupiter test class is of type"),n("code",[e._v("ApplicationContext")]),e._v(" (or a sub-type thereof) or is annotated or meta-annotated with"),n("code",[e._v("@Autowired")]),e._v(", "),n("code",[e._v("@Qualifier")]),e._v(", or "),n("code",[e._v("@Value")]),e._v(", Spring injects the value for that specific\nparameter with the corresponding bean or value from the test’s "),n("code",[e._v("ApplicationContext")]),e._v(".")]),e._v(" "),n("p",[e._v("Spring can also be configured to autowire all arguments for a test class constructor if\nthe constructor is considered to be "),n("em",[e._v("autowirable")]),e._v(". A constructor is considered to be\nautowirable if one of the following conditions is met (in order of precedence).")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("The constructor is annotated with "),n("code",[e._v("@Autowired")]),e._v(".")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("@TestConstructor")]),e._v(" is present or meta-present on the test class with the "),n("code",[e._v("autowireMode")]),e._v("attribute set to "),n("code",[e._v("ALL")]),e._v(".")])]),e._v(" "),n("li",[n("p",[e._v("The default "),n("em",[e._v("test constructor autowire mode")]),e._v(" has been changed to "),n("code",[e._v("ALL")]),e._v(".")])])]),e._v(" "),n("p",[e._v("See "),n("a",{attrs:{href:"#integration-testing-annotations-testconstructor"}},[n("code",[e._v("@TestConstructor")])]),e._v(" for details on the use of"),n("code",[e._v("@TestConstructor")]),e._v(" and how to change the global "),n("em",[e._v("test constructor autowire mode")]),e._v(".")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("If the constructor for a test class is considered to be "),n("em",[e._v("autowirable")]),e._v(", Spring"),n("br"),e._v("assumes the responsibility for resolving arguments for all parameters in the constructor."),n("br"),e._v("Consequently, no other "),n("code",[e._v("ParameterResolver")]),e._v(" registered with JUnit Jupiter can resolve"),n("br"),e._v("parameters for such a constructor.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Constructor injection for test classes must not be used in conjunction with JUnit"),n("br"),e._v("Jupiter’s "),n("code",[e._v("@TestInstance(PER_CLASS)")]),e._v(" support if "),n("code",[e._v("@DirtiesContext")]),e._v(" is used to close the"),n("br"),e._v("test’s "),n("code",[e._v("ApplicationContext")]),e._v(" before or after test methods."),n("br"),n("br"),e._v("The reason is that "),n("code",[e._v("@TestInstance(PER_CLASS)")]),e._v(" instructs JUnit Jupiter to cache the test"),n("br"),e._v("instance between test method invocations. Consequently, the test instance will retain"),n("br"),e._v("references to beans that were originally injected from an "),n("code",[e._v("ApplicationContext")]),e._v(" that has"),n("br"),e._v("been subsequently closed. Since the constructor for the test class will only be invoked"),n("br"),e._v("once in such scenarios, dependency injection will not occur again, and subsequent tests"),n("br"),e._v("will interact with beans from the closed "),n("code",[e._v("ApplicationContext")]),e._v(" which may result in errors."),n("br"),n("br"),e._v("To use "),n("code",[e._v("@DirtiesContext")]),e._v(' with "before test method" or "after test method" modes in'),n("br"),e._v("conjunction with "),n("code",[e._v("@TestInstance(PER_CLASS)")]),e._v(", one must configure dependencies from Spring"),n("br"),e._v("to be supplied via field or setter injection so that they can be re-injected between test"),n("br"),e._v("method invocations.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("In the following example, Spring injects the "),n("code",[e._v("OrderService")]),e._v(" bean from the"),n("code",[e._v("ApplicationContext")]),e._v(" loaded from "),n("code",[e._v("TestConfig.class")]),e._v(" into the"),n("code",[e._v("OrderServiceIntegrationTests")]),e._v(" constructor.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(TestConfig.class)\nclass OrderServiceIntegrationTests {\n\n private final OrderService orderService;\n\n @Autowired\n OrderServiceIntegrationTests(OrderService orderService) {\n this.orderService = orderService;\n }\n\n // tests that use the injected OrderService\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(TestConfig::class)\nclass OrderServiceIntegrationTests @Autowired constructor(private val orderService: OrderService){\n // tests that use the injected OrderService\n}\n")])])]),n("p",[e._v("Note that this feature lets test dependencies be "),n("code",[e._v("final")]),e._v(" and therefore immutable.")]),e._v(" "),n("p",[e._v("If the "),n("code",[e._v("spring.test.constructor.autowire.mode")]),e._v(" property is to "),n("code",[e._v("all")]),e._v(" (see"),n("a",{attrs:{href:"#integration-testing-annotations-testconstructor"}},[n("code",[e._v("@TestConstructor")])]),e._v("), we can omit the declaration of"),n("code",[e._v("@Autowired")]),e._v(" on the constructor in the previous example, resulting in the following.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(TestConfig.class)\nclass OrderServiceIntegrationTests {\n\n private final OrderService orderService;\n\n OrderServiceIntegrationTests(OrderService orderService) {\n this.orderService = orderService;\n }\n\n // tests that use the injected OrderService\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(TestConfig::class)\nclass OrderServiceIntegrationTests(val orderService:OrderService) {\n // tests that use the injected OrderService\n}\n")])])]),n("h6",{attrs:{id:"method-injection"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#method-injection"}},[e._v("#")]),e._v(" Method Injection")]),e._v(" "),n("p",[e._v("If a parameter in a JUnit Jupiter test method or test lifecycle callback method is of\ntype "),n("code",[e._v("ApplicationContext")]),e._v(" (or a sub-type thereof) or is annotated or meta-annotated with"),n("code",[e._v("@Autowired")]),e._v(", "),n("code",[e._v("@Qualifier")]),e._v(", or "),n("code",[e._v("@Value")]),e._v(", Spring injects the value for that specific\nparameter with the corresponding bean from the test’s "),n("code",[e._v("ApplicationContext")]),e._v(".")]),e._v(" "),n("p",[e._v("In the following example, Spring injects the "),n("code",[e._v("OrderService")]),e._v(" from the "),n("code",[e._v("ApplicationContext")]),e._v("loaded from "),n("code",[e._v("TestConfig.class")]),e._v(" into the "),n("code",[e._v("deleteOrder()")]),e._v(" test method:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(TestConfig.class)\nclass OrderServiceIntegrationTests {\n\n @Test\n void deleteOrder(@Autowired OrderService orderService) {\n // use orderService from the test's ApplicationContext\n }\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(TestConfig::class)\nclass OrderServiceIntegrationTests {\n\n @Test\n fun deleteOrder(@Autowired orderService: OrderService) {\n // use orderService from the test's ApplicationContext\n }\n}\n")])])]),n("p",[e._v("Due to the robustness of the "),n("code",[e._v("ParameterResolver")]),e._v(" support in JUnit Jupiter, you can also\nhave multiple dependencies injected into a single method, not only from Spring but also\nfrom JUnit Jupiter itself or other third-party extensions.")]),e._v(" "),n("p",[e._v("The following example shows how to have both Spring and JUnit Jupiter inject dependencies\ninto the "),n("code",[e._v("placeOrderRepeatedly()")]),e._v(" test method simultaneously.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(TestConfig.class)\nclass OrderServiceIntegrationTests {\n\n @RepeatedTest(10)\n void placeOrderRepeatedly(RepetitionInfo repetitionInfo,\n @Autowired OrderService orderService) {\n\n // use orderService from the test's ApplicationContext\n // and repetitionInfo from JUnit Jupiter\n }\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(TestConfig::class)\nclass OrderServiceIntegrationTests {\n\n @RepeatedTest(10)\n fun placeOrderRepeatedly(repetitionInfo:RepetitionInfo, @Autowired orderService:OrderService) {\n\n // use orderService from the test's ApplicationContext\n // and repetitionInfo from JUnit Jupiter\n }\n}\n")])])]),n("p",[e._v("Note that the use of "),n("code",[e._v("@RepeatedTest")]),e._v(" from JUnit Jupiter lets the test method gain access\nto the "),n("code",[e._v("RepetitionInfo")]),e._v(".")]),e._v(" "),n("h5",{attrs:{id:"nested-test-class-configuration"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#nested-test-class-configuration"}},[e._v("#")]),e._v(" "),n("code",[e._v("@Nested")]),e._v(" test class configuration")]),e._v(" "),n("p",[e._v("The "),n("em",[e._v("Spring TestContext Framework")]),e._v(" has supported the use of test-related annotations on"),n("code",[e._v("@Nested")]),e._v(" test classes in JUnit Jupiter since Spring Framework 5.0; however, until Spring\nFramework 5.3 class-level test configuration annotations were not "),n("em",[e._v("inherited")]),e._v(" from\nenclosing classes like they are from superclasses.")]),e._v(" "),n("p",[e._v("Spring Framework 5.3 introduces first-class support for inheriting test class\nconfiguration from enclosing classes, and such configuration will be inherited by\ndefault. To change from the default "),n("code",[e._v("INHERIT")]),e._v(" mode to "),n("code",[e._v("OVERRIDE")]),e._v(" mode, you may annotate\nan individual "),n("code",[e._v("@Nested")]),e._v(" test class with"),n("code",[e._v("@NestedTestConfiguration(EnclosingConfiguration.OVERRIDE)")]),e._v(". An explicit"),n("code",[e._v("@NestedTestConfiguration")]),e._v(" declaration will apply to the annotated test class as well as\nany of its subclasses and nested classes. Thus, you may annotate a top-level test class\nwith "),n("code",[e._v("@NestedTestConfiguration")]),e._v(", and that will apply to all of its nested test classes\nrecursively.")]),e._v(" "),n("p",[e._v("In order to allow development teams to change the default to "),n("code",[e._v("OVERRIDE")]),e._v(" – for example,\nfor compatibility with Spring Framework 5.0 through 5.2 – the default mode can be changed\nglobally via a JVM system property or a "),n("code",[e._v("spring.properties")]),e._v(" file in the root of the\nclasspath. See the "),n("a",{attrs:{href:"#integration-testing-annotations-nestedtestconfiguration"}},[e._v('"Changing\nthe default enclosing configuration inheritance mode"')]),e._v(" note for details.")]),e._v(" "),n("p",[e._v('Although the following "Hello World" example is very simplistic, it shows how to declare\ncommon configuration on a top-level class that is inherited by its '),n("code",[e._v("@Nested")]),e._v(" test\nclasses. In this particular example, only the "),n("code",[e._v("TestConfig")]),e._v(" configuration class is\ninherited. Each nested test class provides its own set of active profiles, resulting in a\ndistinct "),n("code",[e._v("ApplicationContext")]),e._v(" for each nested test class (see"),n("a",{attrs:{href:"#testcontext-ctx-management-caching"}},[e._v("Context Caching")]),e._v(" for details). Consult the list of"),n("a",{attrs:{href:"#integration-testing-annotations-nestedtestconfiguration"}},[e._v("supported annotations")]),e._v(" to see\nwhich annotations can be inherited in "),n("code",[e._v("@Nested")]),e._v(" test classes.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(TestConfig.class)\nclass GreetingServiceTests {\n\n @Nested\n @ActiveProfiles("lang_en")\n class EnglishGreetings {\n\n @Test\n void hello(@Autowired GreetingService service) {\n assertThat(service.greetWorld()).isEqualTo("Hello World");\n }\n }\n\n @Nested\n @ActiveProfiles("lang_de")\n class GermanGreetings {\n\n @Test\n void hello(@Autowired GreetingService service) {\n assertThat(service.greetWorld()).isEqualTo("Hallo Welt");\n }\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitConfig(TestConfig::class)\nclass GreetingServiceTests {\n\n @Nested\n @ActiveProfiles("lang_en")\n inner class EnglishGreetings {\n\n @Test\n fun hello(@Autowired service:GreetingService) {\n assertThat(service.greetWorld()).isEqualTo("Hello World")\n }\n }\n\n @Nested\n @ActiveProfiles("lang_de")\n inner class GermanGreetings {\n\n @Test\n fun hello(@Autowired service:GreetingService) {\n assertThat(service.greetWorld()).isEqualTo("Hallo Welt")\n }\n }\n}\n')])])]),n("h5",{attrs:{id:"testng-support-classes"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#testng-support-classes"}},[e._v("#")]),e._v(" TestNG Support Classes")]),e._v(" "),n("p",[e._v("The "),n("code",[e._v("org.springframework.test.context.testng")]),e._v(" package provides the following support\nclasses for TestNG based test cases:")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("AbstractTestNGSpringContextTests")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("AbstractTransactionalTestNGSpringContextTests")])])])]),e._v(" "),n("p",[n("code",[e._v("AbstractTestNGSpringContextTests")]),e._v(" is an abstract base test class that integrates the\nSpring TestContext Framework with explicit "),n("code",[e._v("ApplicationContext")]),e._v(" testing support in a\nTestNG environment. When you extend "),n("code",[e._v("AbstractTestNGSpringContextTests")]),e._v(", you can access a"),n("code",[e._v("protected")]),e._v(" "),n("code",[e._v("applicationContext")]),e._v(" instance variable that you can use to perform explicit\nbean lookups or to test the state of the context as a whole.")]),e._v(" "),n("p",[n("code",[e._v("AbstractTransactionalTestNGSpringContextTests")]),e._v(" is an abstract transactional extension of"),n("code",[e._v("AbstractTestNGSpringContextTests")]),e._v(" that adds some convenience functionality for JDBC\naccess. This class expects a "),n("code",[e._v("javax.sql.DataSource")]),e._v(" bean and a"),n("code",[e._v("PlatformTransactionManager")]),e._v(" bean to be defined in the "),n("code",[e._v("ApplicationContext")]),e._v(". When you\nextend "),n("code",[e._v("AbstractTransactionalTestNGSpringContextTests")]),e._v(", you can access a "),n("code",[e._v("protected``jdbcTemplate")]),e._v(" instance variable that you can use to run SQL statements to query the\ndatabase. You can use such queries to confirm database state both before and after\nrunning database-related application code, and Spring ensures that such queries run in\nthe scope of the same transaction as the application code. When used in conjunction with\nan ORM tool, be sure to avoid "),n("a",{attrs:{href:"#testcontext-tx-false-positives"}},[e._v("false positives")]),e._v(".\nAs mentioned in "),n("a",{attrs:{href:"#integration-testing-support-jdbc"}},[e._v("JDBC Testing Support")]),e._v(","),n("code",[e._v("AbstractTransactionalTestNGSpringContextTests")]),e._v(" also provides convenience methods that\ndelegate to methods in "),n("code",[e._v("JdbcTestUtils")]),e._v(" by using the aforementioned "),n("code",[e._v("jdbcTemplate")]),e._v(".\nFurthermore, "),n("code",[e._v("AbstractTransactionalTestNGSpringContextTests")]),e._v(" provides an"),n("code",[e._v("executeSqlScript(..)")]),e._v(" method for running SQL scripts against the configured "),n("code",[e._v("DataSource")]),e._v(".")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("These classes are a convenience for extension. If you do not want your test classes"),n("br"),e._v("to be tied to a Spring-specific class hierarchy, you can configure your own custom test"),n("br"),e._v("classes by using "),n("code",[e._v("@ContextConfiguration")]),e._v(", "),n("code",[e._v("@TestExecutionListeners")]),e._v(", and so on and by"),n("br"),e._v("manually instrumenting your test class with a "),n("code",[e._v("TestContextManager")]),e._v(". See the source code"),n("br"),e._v("of "),n("code",[e._v("AbstractTestNGSpringContextTests")]),e._v(" for an example of how to instrument your test class.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h3",{attrs:{id:"_3-6-webtestclient"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-6-webtestclient"}},[e._v("#")]),e._v(" 3.6. WebTestClient")]),e._v(" "),n("p",[n("code",[e._v("WebTestClient")]),e._v(" is an HTTP client designed for testing server applications. It wraps\nSpring’s "),n("RouterLink",{attrs:{to:"/en/spring-framework/web-reactive.html#webflux-client"}},[e._v("WebClient")]),e._v(" and uses it to perform requests\nbut exposes a testing facade for verifying responses. "),n("code",[e._v("WebTestClient")]),e._v(" can be used to\nperform end-to-end HTTP tests. It can also be used to test Spring MVC and Spring WebFlux\napplications without a running server via mock server request and response objects.")],1),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Kotlin users: See "),n("RouterLink",{attrs:{to:"/en/spring-framework/languages.html#kotlin-webtestclient-issue"}},[e._v("this section")]),e._v("related to use of the "),n("code",[e._v("WebTestClient")]),e._v(".")],1)])]),e._v(" "),n("tbody")]),e._v(" "),n("h4",{attrs:{id:"_3-6-1-setup"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-6-1-setup"}},[e._v("#")]),e._v(" 3.6.1. Setup")]),e._v(" "),n("p",[e._v("To set up a "),n("code",[e._v("WebTestClient")]),e._v(" you need to choose a server setup to bind to. This can be one\nof several mock server setup choices or a connection to a live server.")]),e._v(" "),n("h5",{attrs:{id:"bind-to-controller"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#bind-to-controller"}},[e._v("#")]),e._v(" Bind to Controller")]),e._v(" "),n("p",[e._v("This setup allows you to test specific controller(s) via mock request and response objects,\nwithout a running server.")]),e._v(" "),n("p",[e._v("For WebFlux applications, use the following which loads infrastructure equivalent to the"),n("RouterLink",{attrs:{to:"/en/spring-framework/web-reactive.html#webflux-config"}},[e._v("WebFlux Java config")]),e._v(", registers the given\ncontroller(s), and creates a "),n("RouterLink",{attrs:{to:"/en/spring-framework/web-reactive.html#webflux-web-handler-api"}},[e._v("WebHandler chain")]),e._v("to handle requests:")],1),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("WebTestClient client =\n WebTestClient.bindToController(new TestController()).build();\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("val client = WebTestClient.bindToController(TestController()).build()\n")])])]),n("p",[e._v("For Spring MVC, use the following which delegates to the"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilder.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("StandaloneMockMvcBuilder"),n("OutboundLink")],1),e._v("to load infrastructure equivalent to the "),n("RouterLink",{attrs:{to:"/en/spring-framework/web.html#mvc-config"}},[e._v("WebMvc Java config")]),e._v(",\nregisters the given controller(s), and creates an instance of"),n("a",{attrs:{href:"#spring-mvc-test-framework"}},[e._v("MockMvc")]),e._v(" to handle requests:")],1),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("WebTestClient client =\n MockMvcWebTestClient.bindToController(new TestController()).build();\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("val client = MockMvcWebTestClient.bindToController(TestController()).build()\n")])])]),n("h5",{attrs:{id:"bind-to-applicationcontext"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#bind-to-applicationcontext"}},[e._v("#")]),e._v(" Bind to "),n("code",[e._v("ApplicationContext")])]),e._v(" "),n("p",[e._v("This setup allows you to load Spring configuration with Spring MVC or Spring WebFlux\ninfrastructure and controller declarations and use it to handle requests via mock request\nand response objects, without a running server.")]),e._v(" "),n("p",[e._v("For WebFlux, use the following where the Spring "),n("code",[e._v("ApplicationContext")]),e._v(" is passed to"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/web/server/adapter/WebHttpHandlerBuilder.html#applicationContext-org.springframework.context.ApplicationContext-",target:"_blank",rel:"noopener noreferrer"}},[e._v("WebHttpHandlerBuilder"),n("OutboundLink")],1),e._v("to create the "),n("RouterLink",{attrs:{to:"/en/spring-framework/web-reactive.html#webflux-web-handler-api"}},[e._v("WebHandler chain")]),e._v(" to handle\nrequests:")],1),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(WebConfig.class) (1)\nclass MyTests {\n\n WebTestClient client;\n\n @BeforeEach\n void setUp(ApplicationContext context) { (2)\n client = WebTestClient.bindToApplicationContext(context).build(); (3)\n }\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specify the configuration to load")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Inject the configuration")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("3")])]),e._v(" "),n("td",[e._v("Create the "),n("code",[e._v("WebTestClient")])])])])]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@SpringJUnitConfig(WebConfig::class) (1)\nclass MyTests {\n\n lateinit var client: WebTestClient\n\n @BeforeEach\n fun setUp(context: ApplicationContext) { (2)\n client = WebTestClient.bindToApplicationContext(context).build() (3)\n }\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specify the configuration to load")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Inject the configuration")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("3")])]),e._v(" "),n("td",[e._v("Create the "),n("code",[e._v("WebTestClient")])])])])]),e._v(" "),n("p",[e._v("For Spring MVC, use the following where the Spring "),n("code",[e._v("ApplicationContext")]),e._v(" is passed to"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/web/servlet/setup/MockMvcBuilders.html#webAppContextSetup-org.springframework.web.context.WebApplicationContext-",target:"_blank",rel:"noopener noreferrer"}},[e._v("MockMvcBuilders.webAppContextSetup"),n("OutboundLink")],1),e._v("to create a "),n("a",{attrs:{href:"#spring-mvc-test-framework"}},[e._v("MockMvc")]),e._v(" instance to handle\nrequests:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n@WebAppConfiguration("classpath:META-INF/web-resources") (1)\n@ContextHierarchy({\n @ContextConfiguration(classes = RootConfig.class),\n @ContextConfiguration(classes = WebConfig.class)\n})\nclass MyTests {\n\n @Autowired\n WebApplicationContext wac; (2)\n\n WebTestClient client;\n\n @BeforeEach\n void setUp() {\n client = MockMvcWebTestClient.bindToApplicationContext(this.wac).build(); (3)\n }\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specify the configuration to load")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Inject the configuration")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("3")])]),e._v(" "),n("td",[e._v("Create the "),n("code",[e._v("WebTestClient")])])])])]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@ExtendWith(SpringExtension.class)\n@WebAppConfiguration("classpath:META-INF/web-resources") (1)\n@ContextHierarchy({\n @ContextConfiguration(classes = RootConfig.class),\n @ContextConfiguration(classes = WebConfig.class)\n})\nclass MyTests {\n\n @Autowired\n lateinit var wac: WebApplicationContext; (2)\n\n lateinit var client: WebTestClient\n\n @BeforeEach\n fun setUp() { (2)\n client = MockMvcWebTestClient.bindToApplicationContext(wac).build() (3)\n }\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Specify the configuration to load")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Inject the configuration")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("3")])]),e._v(" "),n("td",[e._v("Create the "),n("code",[e._v("WebTestClient")])])])])]),e._v(" "),n("h5",{attrs:{id:"bind-to-router-function"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#bind-to-router-function"}},[e._v("#")]),e._v(" Bind to Router Function")]),e._v(" "),n("p",[e._v("This setup allows you to test "),n("RouterLink",{attrs:{to:"/en/spring-framework/web-reactive.html#webflux-fn"}},[e._v("functional endpoints")]),e._v(" via\nmock request and response objects, without a running server.")],1),e._v(" "),n("p",[e._v("For WebFlux, use the following which delegates to "),n("code",[e._v("RouterFunctions.toWebHandler")]),e._v(" to\ncreate a server setup to handle requests:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("RouterFunction route = ...\nclient = WebTestClient.bindToRouterFunction(route).build();\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("val route: RouterFunction<*> = ...\nval client = WebTestClient.bindToRouterFunction(route).build()\n")])])]),n("p",[e._v("For Spring MVC there are currently no options to test"),n("RouterLink",{attrs:{to:"/en/spring-framework/web.html#webmvc-fn"}},[e._v("WebMvc functional endpoints")]),e._v(".")],1),e._v(" "),n("h5",{attrs:{id:"bind-to-server"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#bind-to-server"}},[e._v("#")]),e._v(" Bind to Server")]),e._v(" "),n("p",[e._v("This setup connects to a running server to perform full, end-to-end HTTP tests:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client = WebTestClient.bindToServer().baseUrl("http://localhost:8080").build();\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client = WebTestClient.bindToServer().baseUrl("http://localhost:8080").build()\n')])])]),n("h5",{attrs:{id:"client-config"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#client-config"}},[e._v("#")]),e._v(" Client Config")]),e._v(" "),n("p",[e._v("In addition to the server setup options described earlier, you can also configure client\noptions, including base URL, default headers, client filters, and others. These options\nare readily available following "),n("code",[e._v("bindToServer()")]),e._v(". For all other configuration options,\nyou need to use "),n("code",[e._v("configureClient()")]),e._v(" to transition from server to client configuration, as\nfollows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client = WebTestClient.bindToController(new TestController())\n .configureClient()\n .baseUrl("/test")\n .build();\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client = WebTestClient.bindToController(TestController())\n .configureClient()\n .baseUrl("/test")\n .build()\n')])])]),n("h4",{attrs:{id:"_3-6-2-writing-tests"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-6-2-writing-tests"}},[e._v("#")]),e._v(" 3.6.2. Writing Tests")]),e._v(" "),n("p",[n("code",[e._v("WebTestClient")]),e._v(" provides an API identical to "),n("RouterLink",{attrs:{to:"/en/spring-framework/web-reactive.html#webflux-client"}},[e._v("WebClient")]),e._v("up to the point of performing a request by using "),n("code",[e._v("exchange()")]),e._v(". See the"),n("RouterLink",{attrs:{to:"/en/spring-framework/web-reactive.html#webflux-client-body"}},[e._v("WebClient")]),e._v(" documentation for examples on how to\nprepare a request with any content including form data, multipart data, and more.")],1),e._v(" "),n("p",[e._v("After the call to "),n("code",[e._v("exchange()")]),e._v(", "),n("code",[e._v("WebTestClient")]),e._v(" diverges from the "),n("code",[e._v("WebClient")]),e._v(" and\ninstead continues with a workflow to verify responses.")]),e._v(" "),n("p",[e._v("To assert the response status and headers, use the following:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.get().uri("/persons/1")\n .accept(MediaType.APPLICATION_JSON)\n .exchange()\n .expectStatus().isOk()\n .expectHeader().contentType(MediaType.APPLICATION_JSON);\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.get().uri("/persons/1")\n .accept(MediaType.APPLICATION_JSON)\n .exchange()\n .expectStatus().isOk()\n .expectHeader().contentType(MediaType.APPLICATION_JSON)\n')])])]),n("p",[e._v("If you would like for all expectations to be asserted even if one of them fails, you can\nuse "),n("code",[e._v("expectAll(..)")]),e._v(" instead of multiple chained "),n("code",[e._v("expect*(..)")]),e._v(" calls. This feature is\nsimilar to the "),n("em",[e._v("soft assertions")]),e._v(" support in AssertJ and the "),n("code",[e._v("assertAll()")]),e._v(" support in\nJUnit Jupiter.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.get().uri("/persons/1")\n .accept(MediaType.APPLICATION_JSON)\n .exchange()\n .expectAll(\n spec -> spec.expectStatus().isOk(),\n spec -> spec.expectHeader().contentType(MediaType.APPLICATION_JSON)\n );\n')])])]),n("p",[e._v("You can then choose to decode the response body through one of the following:")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("expectBody(Class)")]),e._v(": Decode to single object.")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("expectBodyList(Class)")]),e._v(": Decode and collect objects to "),n("code",[e._v("List")]),e._v(".")])]),e._v(" "),n("li",[n("p",[n("code",[e._v("expectBody()")]),e._v(": Decode to "),n("code",[e._v("byte[]")]),e._v(" for "),n("a",{attrs:{href:"#webtestclient-json"}},[e._v("JSON Content")]),e._v(" or an empty body.")])])]),e._v(" "),n("p",[e._v("And perform assertions on the resulting higher level Object(s):")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.get().uri("/persons")\n .exchange()\n .expectStatus().isOk()\n .expectBodyList(Person.class).hasSize(3).contains(person);\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('import org.springframework.test.web.reactive.server.expectBodyList\n\nclient.get().uri("/persons")\n .exchange()\n .expectStatus().isOk()\n .expectBodyList().hasSize(3).contains(person)\n')])])]),n("p",[e._v("If the built-in assertions are insufficient, you can consume the object instead and\nperform any other assertions:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('import org.springframework.test.web.reactive.server.expectBody\n\nclient.get().uri("/persons/1")\n .exchange()\n .expectStatus().isOk()\n .expectBody(Person.class)\n .consumeWith(result -> {\n // custom assertions (e.g. AssertJ)...\n });\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.get().uri("/persons/1")\n .exchange()\n .expectStatus().isOk()\n .expectBody()\n .consumeWith {\n // custom assertions (e.g. AssertJ)...\n }\n')])])]),n("p",[e._v("Or you can exit the workflow and obtain an "),n("code",[e._v("EntityExchangeResult")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('EntityExchangeResult result = client.get().uri("/persons/1")\n .exchange()\n .expectStatus().isOk()\n .expectBody(Person.class)\n .returnResult();\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('import org.springframework.test.web.reactive.server.expectBody\n\nval result = client.get().uri("/persons/1")\n .exchange()\n .expectStatus().isOk\n .expectBody()\n .returnResult()\n')])])]),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("When you need to decode to a target type with generics, look for the overloaded methods"),n("br"),e._v("that accept"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/core/ParameterizedTypeReference.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("ParameterizedTypeReference")]),n("OutboundLink")],1),e._v("instead of "),n("code",[e._v("Class")]),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"no-content"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#no-content"}},[e._v("#")]),e._v(" No Content")]),e._v(" "),n("p",[e._v("If the response is not expected to have content, you can assert that as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.post().uri("/persons")\n .body(personMono, Person.class)\n .exchange()\n .expectStatus().isCreated()\n .expectBody().isEmpty();\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.post().uri("/persons")\n .bodyValue(person)\n .exchange()\n .expectStatus().isCreated()\n .expectBody().isEmpty()\n')])])]),n("p",[e._v("If you want to ignore the response content, the following releases the content without\nany assertions:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.get().uri("/persons/123")\n .exchange()\n .expectStatus().isNotFound()\n .expectBody(Void.class);\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.get().uri("/persons/123")\n .exchange()\n .expectStatus().isNotFound\n .expectBody()\n')])])]),n("h5",{attrs:{id:"json-content"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#json-content"}},[e._v("#")]),e._v(" JSON Content")]),e._v(" "),n("p",[e._v("You can use "),n("code",[e._v("expectBody()")]),e._v(" without a target type to perform assertions on the raw\ncontent rather than through higher level Object(s).")]),e._v(" "),n("p",[e._v("To verify the full JSON content with "),n("a",{attrs:{href:"https://jsonassert.skyscreamer.org",target:"_blank",rel:"noopener noreferrer"}},[e._v("JSONAssert"),n("OutboundLink")],1),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.get().uri("/persons/1")\n .exchange()\n .expectStatus().isOk()\n .expectBody()\n .json("{\\"name\\":\\"Jane\\"}")\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.get().uri("/persons/1")\n .exchange()\n .expectStatus().isOk()\n .expectBody()\n .json("{\\"name\\":\\"Jane\\"}")\n')])])]),n("p",[e._v("To verify JSON content with "),n("a",{attrs:{href:"https://github.com/jayway/JsonPath",target:"_blank",rel:"noopener noreferrer"}},[e._v("JSONPath"),n("OutboundLink")],1),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.get().uri("/persons")\n .exchange()\n .expectStatus().isOk()\n .expectBody()\n .jsonPath("$[0].name").isEqualTo("Jane")\n .jsonPath("$[1].name").isEqualTo("Jason");\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('client.get().uri("/persons")\n .exchange()\n .expectStatus().isOk()\n .expectBody()\n .jsonPath("$[0].name").isEqualTo("Jane")\n .jsonPath("$[1].name").isEqualTo("Jason")\n')])])]),n("h5",{attrs:{id:"streaming-responses"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#streaming-responses"}},[e._v("#")]),e._v(" Streaming Responses")]),e._v(" "),n("p",[e._v("To test potentially infinite streams such as "),n("code",[e._v('"text/event-stream"')]),e._v(" or"),n("code",[e._v('"application/x-ndjson"')]),e._v(", start by verifying the response status and headers, and then\nobtain a "),n("code",[e._v("FluxExchangeResult")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('FluxExchangeResult result = client.get().uri("/events")\n .accept(TEXT_EVENT_STREAM)\n .exchange()\n .expectStatus().isOk()\n .returnResult(MyEvent.class);\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('import org.springframework.test.web.reactive.server.returnResult\n\nval result = client.get().uri("/events")\n .accept(TEXT_EVENT_STREAM)\n .exchange()\n .expectStatus().isOk()\n .returnResult()\n')])])]),n("p",[e._v("Now you’re ready to consume the response stream with "),n("code",[e._v("StepVerifier")]),e._v(" from "),n("code",[e._v("reactor-test")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("Flux eventFlux = result.getResponseBody();\n\nStepVerifier.create(eventFlux)\n .expectNext(person)\n .expectNextCount(4)\n .consumeNextWith(p -> ...)\n .thenCancel()\n .verify();\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("val eventFlux = result.getResponseBody()\n\nStepVerifier.create(eventFlux)\n .expectNext(person)\n .expectNextCount(4)\n .consumeNextWith { p -> ... }\n .thenCancel()\n .verify()\n")])])]),n("h5",{attrs:{id:"mockmvc-assertions"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#mockmvc-assertions"}},[e._v("#")]),e._v(" MockMvc Assertions")]),e._v(" "),n("p",[n("code",[e._v("WebTestClient")]),e._v(" is an HTTP client and as such it can only verify what is in the client\nresponse including status, headers, and body.")]),e._v(" "),n("p",[e._v("When testing a Spring MVC application with a MockMvc server setup, you have the extra\nchoice to perform further assertions on the server response. To do that start by\nobtaining an "),n("code",[e._v("ExchangeResult")]),e._v(" after asserting the body:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// For a response with a body\nEntityExchangeResult result = client.get().uri("/persons/1")\n .exchange()\n .expectStatus().isOk()\n .expectBody(Person.class)\n .returnResult();\n\n// For a response without a body\nEntityExchangeResult result = client.get().uri("/path")\n .exchange()\n .expectBody().isEmpty();\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// For a response with a body\nval result = client.get().uri("/persons/1")\n .exchange()\n .expectStatus().isOk()\n .expectBody(Person.class)\n .returnResult();\n\n// For a response without a body\nval result = client.get().uri("/path")\n .exchange()\n .expectBody().isEmpty();\n')])])]),n("p",[e._v("Then switch to MockMvc server response assertions:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('MockMvcWebTestClient.resultActionsFor(result)\n .andExpect(model().attribute("integer", 3))\n .andExpect(model().attribute("string", "a string value"));\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('MockMvcWebTestClient.resultActionsFor(result)\n .andExpect(model().attribute("integer", 3))\n .andExpect(model().attribute("string", "a string value"));\n')])])]),n("h3",{attrs:{id:"_3-7-mockmvc"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-7-mockmvc"}},[e._v("#")]),e._v(" 3.7. MockMvc")]),e._v(" "),n("p",[e._v("The Spring MVC Test framework, also known as MockMvc, provides support for testing Spring\nMVC applications. It performs full Spring MVC request handling but via mock request and\nresponse objects instead of a running server.")]),e._v(" "),n("p",[e._v("MockMvc can be used on its own to perform requests and verify responses. It can also be\nused through the "),n("a",{attrs:{href:"#webtestclient"}},[e._v("WebTestClient")]),e._v(" where MockMvc is plugged in as the server to handle\nrequests with. The advantage of "),n("code",[e._v("WebTestClient")]),e._v(" is the option to work with higher level\nobjects instead of raw data as well as the ability to switch to full, end-to-end HTTP\ntests against a live server and use the same test API.")]),e._v(" "),n("h4",{attrs:{id:"_3-7-1-overview"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-7-1-overview"}},[e._v("#")]),e._v(" 3.7.1. Overview")]),e._v(" "),n("p",[e._v("You can write plain unit tests for Spring MVC by instantiating a controller, injecting it\nwith dependencies, and calling its methods. However such tests do not verify request\nmappings, data binding, message conversion, type conversion, validation, and nor\ndo they involve any of the supporting "),n("code",[e._v("@InitBinder")]),e._v(", "),n("code",[e._v("@ModelAttribute")]),e._v(", or"),n("code",[e._v("@ExceptionHandler")]),e._v(" methods.")]),e._v(" "),n("p",[e._v("The Spring MVC Test framework, also known as "),n("code",[e._v("MockMvc")]),e._v(", aims to provide more complete\ntesting for Spring MVC controllers without a running server. It does that by invoking\nthe "),n("code",[e._v("DispacherServlet")]),e._v(" and passing"),n("a",{attrs:{href:"#mock-objects-servlet"}},[e._v("“mock” implementations of the Servlet API")]),e._v(" from the"),n("code",[e._v("spring-test")]),e._v(" module which replicates the full Spring MVC request handling without\na running server.")]),e._v(" "),n("p",[e._v("MockMvc is a server side test framework that lets you verify most of the functionality\nof a Spring MVC application using lightweight and targeted tests. You can use it on\nits own to perform requests and to verify responses, or you can also use it through\nthe "),n("a",{attrs:{href:"#webtestclient"}},[e._v("WebTestClient")]),e._v(" API with MockMvc plugged in as the server to handle requests\nwith.")]),e._v(" "),n("h5",{attrs:{id:"static-imports"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#static-imports"}},[e._v("#")]),e._v(" Static Imports")]),e._v(" "),n("p",[e._v("When using MockMvc directly to perform requests, you’ll need static imports for:")]),e._v(" "),n("ul",[n("li",[n("p",[n("code",[e._v("MockMvcBuilders.*")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("MockMvcRequestBuilders.*")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("MockMvcResultMatchers.*")])])]),e._v(" "),n("li",[n("p",[n("code",[e._v("MockMvcResultHandlers.*")])])])]),e._v(" "),n("p",[e._v("An easy way to remember that is search for "),n("code",[e._v("MockMvc*")]),e._v(". If using Eclipse be sure to also\nadd the above as “favorite static members” in the Eclipse preferences.")]),e._v(" "),n("p",[e._v("When using MockMvc through the "),n("a",{attrs:{href:"#webtestclient"}},[e._v("WebTestClient")]),e._v(" you do not need static imports.\nThe "),n("code",[e._v("WebTestClient")]),e._v(" provides a fluent API without static imports.")]),e._v(" "),n("h5",{attrs:{id:"setup-choices"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#setup-choices"}},[e._v("#")]),e._v(" Setup Choices")]),e._v(" "),n("p",[e._v("MockMvc can be setup in one of two ways. One is to point directly to the controllers you\nwant to test and programmatically configure Spring MVC infrastructure. The second is to\npoint to Spring configuration with Spring MVC and controller infrastructure in it.")]),e._v(" "),n("p",[e._v("To set up MockMvc for testing a specific controller, use the following:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("class MyWebTests {\n\n MockMvc mockMvc;\n\n @BeforeEach\n void setup() {\n this.mockMvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();\n }\n\n // ...\n\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("class MyWebTests {\n\n lateinit var mockMvc : MockMvc\n\n @BeforeEach\n fun setup() {\n mockMvc = MockMvcBuilders.standaloneSetup(AccountController()).build()\n }\n\n // ...\n\n}\n")])])]),n("p",[e._v("Or you can also use this setup when testing through the"),n("a",{attrs:{href:"#webtestclient-controller-config"}},[e._v("WebTestClient")]),e._v(" which delegates to the same builder\nas shown above.")]),e._v(" "),n("p",[e._v("To set up MockMvc through Spring configuration, use the following:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitWebConfig(locations = "my-servlet-context.xml")\nclass MyWebTests {\n\n MockMvc mockMvc;\n\n @BeforeEach\n void setup(WebApplicationContext wac) {\n this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();\n }\n\n // ...\n\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitWebConfig(locations = ["my-servlet-context.xml"])\nclass MyWebTests {\n\n lateinit var mockMvc: MockMvc\n\n @BeforeEach\n fun setup(wac: WebApplicationContext) {\n mockMvc = MockMvcBuilders.webAppContextSetup(wac).build()\n }\n\n // ...\n\n}\n')])])]),n("p",[e._v("Or you can also use this setup when testing through the"),n("a",{attrs:{href:"#webtestclient-context-config"}},[e._v("WebTestClient")]),e._v(" which delegates to the same builder\nas shown above.")]),e._v(" "),n("p",[e._v("Which setup option should you use?")]),e._v(" "),n("p",[e._v("The "),n("code",[e._v("webAppContextSetup")]),e._v(" loads your actual Spring MVC configuration, resulting in a more\ncomplete integration test. Since the TestContext framework caches the loaded Spring\nconfiguration, it helps keep tests running fast, even as you introduce more tests in your\ntest suite. Furthermore, you can inject mock services into controllers through Spring\nconfiguration to remain focused on testing the web layer. The following example declares\na mock service with Mockito:")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('\n \n\n')])])]),n("p",[e._v("You can then inject the mock service into the test to set up and verify your\nexpectations, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitWebConfig(locations = "test-servlet-context.xml")\nclass AccountTests {\n\n @Autowired\n AccountService accountService;\n\n MockMvc mockMvc;\n\n @BeforeEach\n void setup(WebApplicationContext wac) {\n this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();\n }\n\n // ...\n\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@SpringJUnitWebConfig(locations = ["test-servlet-context.xml"])\nclass AccountTests {\n\n @Autowired\n lateinit var accountService: AccountService\n\n lateinit mockMvc: MockMvc\n\n @BeforeEach\n fun setup(wac: WebApplicationContext) {\n mockMvc = MockMvcBuilders.webAppContextSetup(wac).build()\n }\n\n // ...\n\n}\n')])])]),n("p",[e._v("The "),n("code",[e._v("standaloneSetup")]),e._v(", on the other hand, is a little closer to a unit test. It tests one\ncontroller at a time. You can manually inject the controller with mock dependencies, and\nit does not involve loading Spring configuration. Such tests are more focused on style\nand make it easier to see which controller is being tested, whether any specific Spring\nMVC configuration is required to work, and so on. The "),n("code",[e._v("standaloneSetup")]),e._v(" is also a very\nconvenient way to write ad-hoc tests to verify specific behavior or to debug an issue.")]),e._v(" "),n("p",[e._v("As with most “integration versus unit testing” debates, there is no right or wrong\nanswer. However, using the "),n("code",[e._v("standaloneSetup")]),e._v(" does imply the need for additional"),n("code",[e._v("webAppContextSetup")]),e._v(" tests in order to verify your Spring MVC configuration.\nAlternatively, you can write all your tests with "),n("code",[e._v("webAppContextSetup")]),e._v(", in order to always\ntest against your actual Spring MVC configuration.")]),e._v(" "),n("h5",{attrs:{id:"setup-features"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#setup-features"}},[e._v("#")]),e._v(" Setup Features")]),e._v(" "),n("p",[e._v("No matter which MockMvc builder you use, all "),n("code",[e._v("MockMvcBuilder")]),e._v(" implementations provide\nsome common and very useful features. For example, you can declare an "),n("code",[e._v("Accept")]),e._v(" header for\nall requests and expect a status of 200 as well as a "),n("code",[e._v("Content-Type")]),e._v(" header in all\nresponses, as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// static import of MockMvcBuilders.standaloneSetup\n\nMockMvc mockMvc = standaloneSetup(new MusicController())\n .defaultRequest(get("/").accept(MediaType.APPLICATION_JSON))\n .alwaysExpect(status().isOk())\n .alwaysExpect(content().contentType("application/json;charset=UTF-8"))\n .build();\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed\n")])])]),n("p",[e._v("In addition, third-party frameworks (and applications) can pre-package setup\ninstructions, such as those in a "),n("code",[e._v("MockMvcConfigurer")]),e._v(". The Spring Framework has one such\nbuilt-in implementation that helps to save and re-use the HTTP session across requests.\nYou can use it as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// static import of SharedHttpSessionConfigurer.sharedHttpSession\n\nMockMvc mockMvc = MockMvcBuilders.standaloneSetup(new TestController())\n .apply(sharedHttpSession())\n .build();\n\n// Use mockMvc to perform requests...\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed\n")])])]),n("p",[e._v("See the javadoc for"),n("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/javadoc-api/org/springframework/test/web/servlet/setup/ConfigurableMockMvcBuilder.html",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("ConfigurableMockMvcBuilder")]),n("OutboundLink")],1),e._v("for a list of all MockMvc builder features or use the IDE to explore the available options.")]),e._v(" "),n("h5",{attrs:{id:"performing-requests"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#performing-requests"}},[e._v("#")]),e._v(" Performing Requests")]),e._v(" "),n("p",[e._v("This section shows how to use MockMvc on its own to perform requests and verify responses.\nIf using MockMvc through the "),n("code",[e._v("WebTestClient")]),e._v(" please see the corresponding section on"),n("a",{attrs:{href:"#webtestclient-tests"}},[e._v("Writing Tests")]),e._v(" instead.")]),e._v(" "),n("p",[e._v("To perform requests that use any HTTP method, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// static import of MockMvcRequestBuilders.*\n\nmockMvc.perform(post("/hotels/{id}", 42).accept(MediaType.APPLICATION_JSON));\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('import org.springframework.test.web.servlet.post\n\nmockMvc.post("/hotels/{id}", 42) {\n accept = MediaType.APPLICATION_JSON\n}\n')])])]),n("p",[e._v("You can also perform file upload requests that internally use"),n("code",[e._v("MockMultipartHttpServletRequest")]),e._v(" so that there is no actual parsing of a multipart\nrequest. Rather, you have to set it up to be similar to the following example:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('mockMvc.perform(multipart("/doc").file("a1", "ABC".getBytes("UTF-8")));\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('import org.springframework.test.web.servlet.multipart\n\nmockMvc.multipart("/doc") {\n file("a1", "ABC".toByteArray(charset("UTF8")))\n}\n')])])]),n("p",[e._v("You can specify query parameters in URI template style, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('mockMvc.perform(get("/hotels?thing={thing}", "somewhere"));\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('mockMvc.get("/hotels?thing={thing}", "somewhere")\n')])])]),n("p",[e._v("You can also add Servlet request parameters that represent either query or form\nparameters, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('mockMvc.perform(get("/hotels").param("thing", "somewhere"));\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('import org.springframework.test.web.servlet.get\n\nmockMvc.get("/hotels") {\n param("thing", "somewhere")\n}\n')])])]),n("p",[e._v("If application code relies on Servlet request parameters and does not check the query\nstring explicitly (as is most often the case), it does not matter which option you use.\nKeep in mind, however, that query parameters provided with the URI template are decoded\nwhile request parameters provided through the "),n("code",[e._v("param(…​)")]),e._v(" method are expected to already\nbe decoded.")]),e._v(" "),n("p",[e._v("In most cases, it is preferable to leave the context path and the Servlet path out of the\nrequest URI. If you must test with the full request URI, be sure to set the "),n("code",[e._v("contextPath")]),e._v("and "),n("code",[e._v("servletPath")]),e._v(" accordingly so that request mappings work, as the following example\nshows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('mockMvc.perform(get("/app/main/hotels/{id}").contextPath("/app").servletPath("/main"))\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('import org.springframework.test.web.servlet.get\n\nmockMvc.get("/app/main/hotels/{id}") {\n contextPath = "/app"\n servletPath = "/main"\n}\n')])])]),n("p",[e._v("In the preceding example, it would be cumbersome to set the "),n("code",[e._v("contextPath")]),e._v(" and"),n("code",[e._v("servletPath")]),e._v(" with every performed request. Instead, you can set up default request\nproperties, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('class MyWebTests {\n\n MockMvc mockMvc;\n\n @BeforeEach\n void setup() {\n mockMvc = standaloneSetup(new AccountController())\n .defaultRequest(get("/")\n .contextPath("/app").servletPath("/main")\n .accept(MediaType.APPLICATION_JSON)).build();\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed\n")])])]),n("p",[e._v("The preceding properties affect every request performed through the "),n("code",[e._v("MockMvc")]),e._v(" instance.\nIf the same property is also specified on a given request, it overrides the default\nvalue. That is why the HTTP method and URI in the default request do not matter, since\nthey must be specified on every request.")]),e._v(" "),n("h5",{attrs:{id:"defining-expectations"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#defining-expectations"}},[e._v("#")]),e._v(" Defining Expectations")]),e._v(" "),n("p",[e._v("You can define expectations by appending one or more "),n("code",[e._v("andExpect(..)")]),e._v(" calls after\nperforming a request, as the following example shows. As soon as one expectation fails,\nno other expectations will be asserted.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// static import of MockMvcRequestBuilders.* and MockMvcResultMatchers.*\n\nmockMvc.perform(get("/accounts/1")).andExpect(status().isOk());\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('import org.springframework.test.web.servlet.get\n\nmockMvc.get("/accounts/1").andExpect {\n status().isOk()\n}\n')])])]),n("p",[e._v("You can define multiple expectations by appending "),n("code",[e._v("andExpectAll(..)")]),e._v(" after performing a\nrequest, as the following example shows. In contrast to "),n("code",[e._v("andExpect(..)")]),e._v(","),n("code",[e._v("andExpectAll(..)")]),e._v(" guarantees that all supplied expectations will be asserted and that\nall failures will be tracked and reported.")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// static import of MockMvcRequestBuilders.* and MockMvcResultMatchers.*\n\nmockMvc.perform(get("/accounts/1")).andExpectAll(\n status().isOk(),\n content().contentType("application/json;charset=UTF-8"));\n')])])]),n("p",[n("code",[e._v("MockMvcResultMatchers.*")]),e._v(" provides a number of expectations, some of which are further\nnested with more detailed expectations.")]),e._v(" "),n("p",[e._v("Expectations fall in two general categories. The first category of assertions verifies\nproperties of the response (for example, the response status, headers, and content).\nThese are the most important results to assert.")]),e._v(" "),n("p",[e._v("The second category of assertions goes beyond the response. These assertions let you\ninspect Spring MVC specific aspects, such as which controller method processed the\nrequest, whether an exception was raised and handled, what the content of the model is,\nwhat view was selected, what flash attributes were added, and so on. They also let you\ninspect Servlet specific aspects, such as request and session attributes.")]),e._v(" "),n("p",[e._v("The following test asserts that binding or validation failed:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('mockMvc.perform(post("/persons"))\n .andExpect(status().isOk())\n .andExpect(model().attributeHasErrors("person"));\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('import org.springframework.test.web.servlet.post\n\nmockMvc.post("/persons").andExpect {\n status().isOk()\n model {\n attributeHasErrors("person")\n }\n}\n')])])]),n("p",[e._v("Many times, when writing tests, it is useful to dump the results of the performed\nrequest. You can do so as follows, where "),n("code",[e._v("print()")]),e._v(" is a static import from"),n("code",[e._v("MockMvcResultHandlers")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('mockMvc.perform(post("/persons"))\n .andDo(print())\n .andExpect(status().isOk())\n .andExpect(model().attributeHasErrors("person"));\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('import org.springframework.test.web.servlet.post\n\nmockMvc.post("/persons").andDo {\n print()\n }.andExpect {\n status().isOk()\n model {\n attributeHasErrors("person")\n }\n }\n')])])]),n("p",[e._v("As long as request processing does not cause an unhandled exception, the "),n("code",[e._v("print()")]),e._v(" method\nprints all the available result data to "),n("code",[e._v("System.out")]),e._v(". There is also a "),n("code",[e._v("log()")]),e._v(" method and\ntwo additional variants of the "),n("code",[e._v("print()")]),e._v(" method, one that accepts an "),n("code",[e._v("OutputStream")]),e._v(" and\none that accepts a "),n("code",[e._v("Writer")]),e._v(". For example, invoking "),n("code",[e._v("print(System.err)")]),e._v(" prints the result\ndata to "),n("code",[e._v("System.err")]),e._v(", while invoking "),n("code",[e._v("print(myWriter)")]),e._v(" prints the result data to a custom\nwriter. If you want to have the result data logged instead of printed, you can invoke the"),n("code",[e._v("log()")]),e._v(" method, which logs the result data as a single "),n("code",[e._v("DEBUG")]),e._v(" message under the"),n("code",[e._v("org.springframework.test.web.servlet.result")]),e._v(" logging category.")]),e._v(" "),n("p",[e._v("In some cases, you may want to get direct access to the result and verify something that\ncannot be verified otherwise. This can be achieved by appending "),n("code",[e._v(".andReturn()")]),e._v(" after all\nother expectations, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('MvcResult mvcResult = mockMvc.perform(post("/persons")).andExpect(status().isOk()).andReturn();\n// ...\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('var mvcResult = mockMvc.post("/persons").andExpect { status().isOk() }.andReturn()\n// ...\n')])])]),n("p",[e._v("If all tests repeat the same expectations, you can set up common expectations once when\nbuilding the "),n("code",[e._v("MockMvc")]),e._v(" instance, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('standaloneSetup(new SimpleController())\n .alwaysExpect(status().isOk())\n .alwaysExpect(content().contentType("application/json;charset=UTF-8"))\n .build()\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed\n")])])]),n("p",[e._v("Note that common expectations are always applied and cannot be overridden without\ncreating a separate "),n("code",[e._v("MockMvc")]),e._v(" instance.")]),e._v(" "),n("p",[e._v("When a JSON response content contains hypermedia links created with"),n("a",{attrs:{href:"https://github.com/spring-projects/spring-hateoas",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring HATEOAS"),n("OutboundLink")],1),e._v(", you can verify the\nresulting links by using JsonPath expressions, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('mockMvc.perform(get("/people").accept(MediaType.APPLICATION_JSON))\n .andExpect(jsonPath("$.links[?(@.rel == \'self\')].href").value("http://localhost:8080/people"));\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('mockMvc.get("/people") {\n accept(MediaType.APPLICATION_JSON)\n}.andExpect {\n jsonPath("$.links[?(@.rel == \'self\')].href") {\n value("http://localhost:8080/people")\n }\n}\n')])])]),n("p",[e._v("When XML response content contains hypermedia links created with"),n("a",{attrs:{href:"https://github.com/spring-projects/spring-hateoas",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring HATEOAS"),n("OutboundLink")],1),e._v(", you can verify the\nresulting links by using XPath expressions:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('Map ns = Collections.singletonMap("ns", "http://www.w3.org/2005/Atom");\nmockMvc.perform(get("/handle").accept(MediaType.APPLICATION_XML))\n .andExpect(xpath("/person/ns:link[@rel=\'self\']/@href", ns).string("http://localhost:8080/people"));\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('val ns = mapOf("ns" to "http://www.w3.org/2005/Atom")\nmockMvc.get("/handle") {\n accept(MediaType.APPLICATION_XML)\n}.andExpect {\n xpath("/person/ns:link[@rel=\'self\']/@href", ns) {\n string("http://localhost:8080/people")\n }\n}\n')])])]),n("h5",{attrs:{id:"async-requests"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#async-requests"}},[e._v("#")]),e._v(" Async Requests")]),e._v(" "),n("p",[e._v("This section shows how to use MockMvc on its own to test asynchronous request handling.\nIf using MockMvc through the "),n("a",{attrs:{href:"#webtestclient"}},[e._v("WebTestClient")]),e._v(", there is nothing special to do to make\nasynchronous requests work as the "),n("code",[e._v("WebTestClient")]),e._v(" automatically does what is described\nin this section.")]),e._v(" "),n("p",[e._v("Servlet 3.0 asynchronous requests,"),n("RouterLink",{attrs:{to:"/en/spring-framework/web.html#mvc-ann-async"}},[e._v("supported in Spring MVC")]),e._v(", work by exiting the Servlet container\nthread and allowing the application to compute the response asynchronously, after which\nan async dispatch is made to complete processing on a Servlet container thread.")],1),e._v(" "),n("p",[e._v("In Spring MVC Test, async requests can be tested by asserting the produced async value\nfirst, then manually performing the async dispatch, and finally verifying the response.\nBelow is an example test for controller methods that return "),n("code",[e._v("DeferredResult")]),e._v(", "),n("code",[e._v("Callable")]),e._v(",\nor reactive type such as Reactor "),n("code",[e._v("Mono")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('// static import of MockMvcRequestBuilders.* and MockMvcResultMatchers.*\n\n@Test\nvoid test() throws Exception {\n MvcResult mvcResult = this.mockMvc.perform(get("/path"))\n .andExpect(status().isOk()) (1)\n .andExpect(request().asyncStarted()) (2)\n .andExpect(request().asyncResult("body")) (3)\n .andReturn();\n\n this.mockMvc.perform(asyncDispatch(mvcResult)) (4)\n .andExpect(status().isOk()) (5)\n .andExpect(content().string("body"));\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Check response status is still unchanged")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Async processing must have started")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("3")])]),e._v(" "),n("td",[e._v("Wait and assert the async result")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("4")])]),e._v(" "),n("td",[e._v("Manually perform an ASYNC dispatch (as there is no running container)")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("5")])]),e._v(" "),n("td",[e._v("Verify the final response")])])])]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\nfun test() {\n var mvcResult = mockMvc.get("/path").andExpect {\n status().isOk() (1)\n request { asyncStarted() } (2)\n // TODO Remove unused generic parameter\n request { asyncResult("body") } (3)\n }.andReturn()\n\n mockMvc.perform(asyncDispatch(mvcResult)) (4)\n .andExpect {\n status().isOk() (5)\n content().string("body")\n }\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[e._v("Check response status is still unchanged")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("Async processing must have started")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("3")])]),e._v(" "),n("td",[e._v("Wait and assert the async result")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("4")])]),e._v(" "),n("td",[e._v("Manually perform an ASYNC dispatch (as there is no running container)")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("5")])]),e._v(" "),n("td",[e._v("Verify the final response")])])])]),e._v(" "),n("h5",{attrs:{id:"streaming-responses-2"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#streaming-responses-2"}},[e._v("#")]),e._v(" Streaming Responses")]),e._v(" "),n("p",[e._v("The best way to test streaming responses such as Server-Sent Events is through the"),n("a",{attrs:{href:"#webtestclient"}},[e._v("WebTestClient")]),e._v(" which can be used as a test client to connect to a "),n("code",[e._v("MockMvc")]),e._v(" instance\nto perform tests on Spring MVC controllers without a running server. For example:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('WebTestClient client = MockMvcWebTestClient.bindToController(new SseController()).build();\n\nFluxExchangeResult exchangeResult = client.get()\n .uri("/persons")\n .exchange()\n .expectStatus().isOk()\n .expectHeader().contentType("text/event-stream")\n .returnResult(Person.class);\n\n// Use StepVerifier from Project Reactor to test the streaming response\n\nStepVerifier.create(exchangeResult.getResponseBody())\n .expectNext(new Person("N0"), new Person("N1"), new Person("N2"))\n .expectNextCount(4)\n .consumeNextWith(person -> assertThat(person.getName()).endsWith("7"))\n .thenCancel()\n .verify();\n')])])]),n("p",[n("code",[e._v("WebTestClient")]),e._v(" can also connect to a live server and perform full end-to-end integration\ntests. This is also supported in Spring Boot where you can"),n("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-testing-spring-boot-applications-testing-with-running-server",target:"_blank",rel:"noopener noreferrer"}},[e._v("test a running server"),n("OutboundLink")],1),e._v(".")]),e._v(" "),n("h5",{attrs:{id:"filter-registrations"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#filter-registrations"}},[e._v("#")]),e._v(" Filter Registrations")]),e._v(" "),n("p",[e._v("When setting up a "),n("code",[e._v("MockMvc")]),e._v(" instance, you can register one or more Servlet "),n("code",[e._v("Filter")]),e._v("instances, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("mockMvc = standaloneSetup(new PersonController()).addFilters(new CharacterEncodingFilter()).build();\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed\n")])])]),n("p",[e._v("Registered filters are invoked through the "),n("code",[e._v("MockFilterChain")]),e._v(" from "),n("code",[e._v("spring-test")]),e._v(", and the\nlast filter delegates to the "),n("code",[e._v("DispatcherServlet")]),e._v(".")]),e._v(" "),n("h5",{attrs:{id:"mockmvc-vs-end-to-end-tests"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#mockmvc-vs-end-to-end-tests"}},[e._v("#")]),e._v(" MockMvc vs End-to-End Tests")]),e._v(" "),n("p",[e._v("MockMVc is built on Servlet API mock implementations from the"),n("code",[e._v("spring-test")]),e._v(" module and does not rely on a running container. Therefore, there are\nsome differences when compared to full end-to-end integration tests with an actual\nclient and a live server running.")]),e._v(" "),n("p",[e._v("The easiest way to think about this is by starting with a blank "),n("code",[e._v("MockHttpServletRequest")]),e._v(".\nWhatever you add to it is what the request becomes. Things that may catch you by surprise\nare that there is no context path by default; no "),n("code",[e._v("jsessionid")]),e._v(" cookie; no forwarding,\nerror, or async dispatches; and, therefore, no actual JSP rendering. Instead,\n“forwarded” and “redirected” URLs are saved in the "),n("code",[e._v("MockHttpServletResponse")]),e._v(" and can\nbe asserted with expectations.")]),e._v(" "),n("p",[e._v("This means that, if you use JSPs, you can verify the JSP page to which the request was\nforwarded, but no HTML is rendered. In other words, the JSP is not invoked. Note,\nhowever, that all other rendering technologies that do not rely on forwarding, such as\nThymeleaf and Freemarker, render HTML to the response body as expected. The same is true\nfor rendering JSON, XML, and other formats through "),n("code",[e._v("@ResponseBody")]),e._v(" methods.")]),e._v(" "),n("p",[e._v("Alternatively, you may consider the full end-to-end integration testing support from\nSpring Boot with "),n("code",[e._v("@SpringBootTest")]),e._v(". See the"),n("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-testing",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Boot Reference Guide"),n("OutboundLink")],1),e._v(".")]),e._v(" "),n("p",[e._v("There are pros and cons for each approach. The options provided in Spring MVC Test are\ndifferent stops on the scale from classic unit testing to full integration testing. To be\ncertain, none of the options in Spring MVC Test fall under the category of classic unit\ntesting, but they are a little closer to it. For example, you can isolate the web layer\nby injecting mocked services into controllers, in which case you are testing the web\nlayer only through the "),n("code",[e._v("DispatcherServlet")]),e._v(" but with actual Spring configuration, as you\nmight test the data access layer in isolation from the layers above it. Also, you can use\nthe stand-alone setup, focusing on one controller at a time and manually providing the\nconfiguration required to make it work.")]),e._v(" "),n("p",[e._v("Another important distinction when using Spring MVC Test is that, conceptually, such\ntests are the server-side, so you can check what handler was used, if an exception was\nhandled with a HandlerExceptionResolver, what the content of the model is, what binding\nerrors there were, and other details. That means that it is easier to write expectations,\nsince the server is not an opaque box, as it is when testing it through an actual HTTP\nclient. This is generally an advantage of classic unit testing: It is easier to write,\nreason about, and debug but does not replace the need for full integration tests. At the\nsame time, it is important not to lose sight of the fact that the response is the most\nimportant thing to check. In short, there is room here for multiple styles and strategies\nof testing even within the same project.")]),e._v(" "),n("h5",{attrs:{id:"further-examples"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#further-examples"}},[e._v("#")]),e._v(" Further Examples")]),e._v(" "),n("p",[e._v("The framework’s own tests include"),n("a",{attrs:{href:"https://github.com/spring-projects/spring-framework/tree/main/spring-test/src/test/java/org/springframework/test/web/servlet/samples",target:"_blank",rel:"noopener noreferrer"}},[e._v("many sample tests"),n("OutboundLink")],1),e._v(" intended to show how to use MockMvc on its own or through the"),n("a",{attrs:{href:"https://github.com/spring-projects/spring-framework/tree/main/spring-test/src/test/java/org/springframework/test/web/servlet/samples/client",target:"_blank",rel:"noopener noreferrer"}},[e._v("WebTestClient"),n("OutboundLink")],1),e._v(". Browse these examples for further ideas.")]),e._v(" "),n("h4",{attrs:{id:"_3-7-2-htmlunit-integration"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-7-2-htmlunit-integration"}},[e._v("#")]),e._v(" 3.7.2. HtmlUnit Integration")]),e._v(" "),n("p",[e._v("Spring provides integration between "),n("a",{attrs:{href:"#spring-mvc-test-server"}},[e._v("MockMvc")]),e._v(" and"),n("a",{attrs:{href:"http://htmlunit.sourceforge.net/",target:"_blank",rel:"noopener noreferrer"}},[e._v("HtmlUnit"),n("OutboundLink")],1),e._v(". This simplifies performing end-to-end testing\nwhen using HTML-based views. This integration lets you:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("Easily test HTML pages by using tools such as"),n("a",{attrs:{href:"http://htmlunit.sourceforge.net/",target:"_blank",rel:"noopener noreferrer"}},[e._v("HtmlUnit"),n("OutboundLink")],1),e._v(","),n("a",{attrs:{href:"https://www.seleniumhq.org",target:"_blank",rel:"noopener noreferrer"}},[e._v("WebDriver"),n("OutboundLink")],1),e._v(", and"),n("a",{attrs:{href:"http://www.gebish.org/manual/current/#spock-junit-testng",target:"_blank",rel:"noopener noreferrer"}},[e._v("Geb"),n("OutboundLink")],1),e._v(" without the need to\ndeploy to a Servlet container.")])]),e._v(" "),n("li",[n("p",[e._v("Test JavaScript within pages.")])]),e._v(" "),n("li",[n("p",[e._v("Optionally, test using mock services to speed up testing.")])]),e._v(" "),n("li",[n("p",[e._v("Share logic between in-container end-to-end tests and out-of-container integration tests.")])])]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("MockMvc works with templating technologies that do not rely on a Servlet Container"),n("br"),e._v("(for example, Thymeleaf, FreeMarker, and others), but it does not work with JSPs, since"),n("br"),e._v("they rely on the Servlet container.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"why-htmlunit-integration"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#why-htmlunit-integration"}},[e._v("#")]),e._v(" Why HtmlUnit Integration?")]),e._v(" "),n("p",[e._v("The most obvious question that comes to mind is “Why do I need this?” The answer is\nbest found by exploring a very basic sample application. Assume you have a Spring MVC web\napplication that supports CRUD operations on a "),n("code",[e._v("Message")]),e._v(" object. The application also\nsupports paging through all messages. How would you go about testing it?")]),e._v(" "),n("p",[e._v("With Spring MVC Test, we can easily test if we are able to create a "),n("code",[e._v("Message")]),e._v(", as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('MockHttpServletRequestBuilder createMessage = post("/messages/")\n .param("summary", "Spring Rocks")\n .param("text", "In case you didn\'t know, Spring Rocks!");\n\nmockMvc.perform(createMessage)\n .andExpect(status().is3xxRedirection())\n .andExpect(redirectedUrl("/messages/123"));\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('@Test\nfun test() {\n mockMvc.post("/messages/") {\n param("summary", "Spring Rocks")\n param("text", "In case you didn\'t know, Spring Rocks!")\n }.andExpect {\n status().is3xxRedirection()\n redirectedUrl("/messages/123")\n }\n}\n')])])]),n("p",[e._v("What if we want to test the form view that lets us create the message? For example,\nassume our form looks like the following snippet:")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('
\n \n\n \n \n\n \n \n\n
\n \n
\n
\n')])])]),n("p",[e._v("How do we ensure that our form produce the correct request to create a new message? A\nnaive attempt might resemble the following:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('mockMvc.perform(get("/messages/form"))\n .andExpect(xpath("//input[@name=\'summary\']").exists())\n .andExpect(xpath("//textarea[@name=\'text\']").exists());\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('mockMvc.get("/messages/form").andExpect {\n xpath("//input[@name=\'summary\']") { exists() }\n xpath("//textarea[@name=\'text\']") { exists() }\n}\n')])])]),n("p",[e._v("This test has some obvious drawbacks. If we update our controller to use the parameter"),n("code",[e._v("message")]),e._v(" instead of "),n("code",[e._v("text")]),e._v(", our form test continues to pass, even though the HTML form\nis out of synch with the controller. To resolve this we can combine our two tests, as\nfollows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('String summaryParamName = "summary";\nString textParamName = "text";\nmockMvc.perform(get("/messages/form"))\n .andExpect(xpath("//input[@name=\'" + summaryParamName + "\']").exists())\n .andExpect(xpath("//textarea[@name=\'" + textParamName + "\']").exists());\n\nMockHttpServletRequestBuilder createMessage = post("/messages/")\n .param(summaryParamName, "Spring Rocks")\n .param(textParamName, "In case you didn\'t know, Spring Rocks!");\n\nmockMvc.perform(createMessage)\n .andExpect(status().is3xxRedirection())\n .andExpect(redirectedUrl("/messages/123"));\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('val summaryParamName = "summary";\nval textParamName = "text";\nmockMvc.get("/messages/form").andExpect {\n xpath("//input[@name=\'$summaryParamName\']") { exists() }\n xpath("//textarea[@name=\'$textParamName\']") { exists() }\n}\nmockMvc.post("/messages/") {\n param(summaryParamName, "Spring Rocks")\n param(textParamName, "In case you didn\'t know, Spring Rocks!")\n}.andExpect {\n status().is3xxRedirection()\n redirectedUrl("/messages/123")\n}\n')])])]),n("p",[e._v("This would reduce the risk of our test incorrectly passing, but there are still some\nproblems:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("What if we have multiple forms on our page? Admittedly, we could update our XPath\nexpressions, but they get more complicated as we take more factors into account: Are\nthe fields the correct type? Are the fields enabled? And so on.")])]),e._v(" "),n("li",[n("p",[e._v("Another issue is that we are doing double the work we would expect. We must first\nverify the view, and then we submit the view with the same parameters we just verified.\nIdeally, this could be done all at once.")])]),e._v(" "),n("li",[n("p",[e._v("Finally, we still cannot account for some things. For example, what if the form has\nJavaScript validation that we wish to test as well?")])])]),e._v(" "),n("p",[e._v("The overall problem is that testing a web page does not involve a single interaction.\nInstead, it is a combination of how the user interacts with a web page and how that web\npage interacts with other resources. For example, the result of a form view is used as\nthe input to a user for creating a message. In addition, our form view can potentially\nuse additional resources that impact the behavior of the page, such as JavaScript\nvalidation.")]),e._v(" "),n("h6",{attrs:{id:"integration-testing-to-the-rescue"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#integration-testing-to-the-rescue"}},[e._v("#")]),e._v(" Integration Testing to the Rescue?")]),e._v(" "),n("p",[e._v("To resolve the issues mentioned earlier, we could perform end-to-end integration testing,\nbut this has some drawbacks. Consider testing the view that lets us page through the\nmessages. We might need the following tests:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("Does our page display a notification to the user to indicate that no results are\navailable when the messages are empty?")])]),e._v(" "),n("li",[n("p",[e._v("Does our page properly display a single message?")])]),e._v(" "),n("li",[n("p",[e._v("Does our page properly support paging?")])])]),e._v(" "),n("p",[e._v("To set up these tests, we need to ensure our database contains the proper messages. This\nleads to a number of additional challenges:")]),e._v(" "),n("ul",[n("li",[n("p",[e._v("Ensuring the proper messages are in the database can be tedious. (Consider foreign key\nconstraints.)")])]),e._v(" "),n("li",[n("p",[e._v("Testing can become slow, since each test would need to ensure that the database is in\nthe correct state.")])]),e._v(" "),n("li",[n("p",[e._v("Since our database needs to be in a specific state, we cannot run tests in parallel.")])]),e._v(" "),n("li",[n("p",[e._v("Performing assertions on such items as auto-generated ids, timestamps, and others can\nbe difficult.")])])]),e._v(" "),n("p",[e._v("These challenges do not mean that we should abandon end-to-end integration testing\naltogether. Instead, we can reduce the number of end-to-end integration tests by\nrefactoring our detailed tests to use mock services that run much faster, more reliably,\nand without side effects. We can then implement a small number of true end-to-end\nintegration tests that validate simple workflows to ensure that everything works together\nproperly.")]),e._v(" "),n("h6",{attrs:{id:"enter-htmlunit-integration"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#enter-htmlunit-integration"}},[e._v("#")]),e._v(" Enter HtmlUnit Integration")]),e._v(" "),n("p",[e._v("So how can we achieve a balance between testing the interactions of our pages and still\nretain good performance within our test suite? The answer is: “By integrating MockMvc\nwith HtmlUnit.”")]),e._v(" "),n("h6",{attrs:{id:"htmlunit-integration-options"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#htmlunit-integration-options"}},[e._v("#")]),e._v(" HtmlUnit Integration Options")]),e._v(" "),n("p",[e._v("You have a number of options when you want to integrate MockMvc with HtmlUnit:")]),e._v(" "),n("ul",[n("li",[n("p",[n("a",{attrs:{href:"#spring-mvc-test-server-htmlunit-mah"}},[e._v("MockMvc and HtmlUnit")]),e._v(": Use this option if you\nwant to use the raw HtmlUnit libraries.")])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-mvc-test-server-htmlunit-webdriver"}},[e._v("MockMvc and WebDriver")]),e._v(": Use this option to\nease development and reuse code between integration and end-to-end testing.")])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"#spring-mvc-test-server-htmlunit-geb"}},[e._v("MockMvc and Geb")]),e._v(": Use this option if you want to\nuse Groovy for testing, ease development, and reuse code between integration and\nend-to-end testing.")])])]),e._v(" "),n("h5",{attrs:{id:"mockmvc-and-htmlunit"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#mockmvc-and-htmlunit"}},[e._v("#")]),e._v(" MockMvc and HtmlUnit")]),e._v(" "),n("p",[e._v("This section describes how to integrate MockMvc and HtmlUnit. Use this option if you want\nto use the raw HtmlUnit libraries.")]),e._v(" "),n("h6",{attrs:{id:"mockmvc-and-htmlunit-setup"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#mockmvc-and-htmlunit-setup"}},[e._v("#")]),e._v(" MockMvc and HtmlUnit Setup")]),e._v(" "),n("p",[e._v("First, make sure that you have included a test dependency on"),n("code",[e._v("net.sourceforge.htmlunit:htmlunit")]),e._v(". In order to use HtmlUnit with Apache HttpComponents\n4.5+, you need to use HtmlUnit 2.18 or higher.")]),e._v(" "),n("p",[e._v("We can easily create an HtmlUnit "),n("code",[e._v("WebClient")]),e._v(" that integrates with MockMvc by using the"),n("code",[e._v("MockMvcWebClientBuilder")]),e._v(", as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("WebClient webClient;\n\n@BeforeEach\nvoid setup(WebApplicationContext context) {\n webClient = MockMvcWebClientBuilder\n .webAppContextSetup(context)\n .build();\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("lateinit var webClient: WebClient\n\n@BeforeEach\nfun setup(context: WebApplicationContext) {\n webClient = MockMvcWebClientBuilder\n .webAppContextSetup(context)\n .build()\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("This is a simple example of using "),n("code",[e._v("MockMvcWebClientBuilder")]),e._v(". For advanced usage,"),n("br"),e._v("see "),n("a",{attrs:{href:"#spring-mvc-test-server-htmlunit-mah-advanced-builder"}},[e._v("Advanced "),n("code",[e._v("MockMvcWebClientBuilder")])]),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("This ensures that any URL that references "),n("code",[e._v("localhost")]),e._v(" as the server is directed to our"),n("code",[e._v("MockMvc")]),e._v(" instance without the need for a real HTTP connection. Any other URL is\nrequested by using a network connection, as normal. This lets us easily test the use of\nCDNs.")]),e._v(" "),n("h6",{attrs:{id:"mockmvc-and-htmlunit-usage"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#mockmvc-and-htmlunit-usage"}},[e._v("#")]),e._v(" MockMvc and HtmlUnit Usage")]),e._v(" "),n("p",[e._v("Now we can use HtmlUnit as we normally would but without the need to deploy our\napplication to a Servlet container. For example, we can request the view to create a\nmessage with the following:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('HtmlPage createMsgFormPage = webClient.getPage("http://localhost/messages/form");\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('val createMsgFormPage = webClient.getPage("http://localhost/messages/form")\n')])])]),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("The default context path is "),n("code",[e._v('""')]),e._v(". Alternatively, we can specify the context path,"),n("br"),e._v("as described in "),n("a",{attrs:{href:"#spring-mvc-test-server-htmlunit-mah-advanced-builder"}},[e._v("Advanced "),n("code",[e._v("MockMvcWebClientBuilder")])]),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Once we have a reference to the "),n("code",[e._v("HtmlPage")]),e._v(", we can then fill out the form and submit it\nto create a message, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('HtmlForm form = createMsgFormPage.getHtmlElementById("messageForm");\nHtmlTextInput summaryInput = createMsgFormPage.getHtmlElementById("summary");\nsummaryInput.setValueAttribute("Spring Rocks");\nHtmlTextArea textInput = createMsgFormPage.getHtmlElementById("text");\ntextInput.setText("In case you didn\'t know, Spring Rocks!");\nHtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit");\nHtmlPage newMessagePage = submit.click();\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('val form = createMsgFormPage.getHtmlElementById("messageForm")\nval summaryInput = createMsgFormPage.getHtmlElementById("summary")\nsummaryInput.setValueAttribute("Spring Rocks")\nval textInput = createMsgFormPage.getHtmlElementById("text")\ntextInput.setText("In case you didn\'t know, Spring Rocks!")\nval submit = form.getOneHtmlElementByAttribute("input", "type", "submit")\nval newMessagePage = submit.click()\n')])])]),n("p",[e._v("Finally, we can verify that a new message was created successfully. The following\nassertions use the "),n("a",{attrs:{href:"https://assertj.github.io/doc/",target:"_blank",rel:"noopener noreferrer"}},[e._v("AssertJ"),n("OutboundLink")],1),e._v(" library:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('assertThat(newMessagePage.getUrl().toString()).endsWith("/messages/123");\nString id = newMessagePage.getHtmlElementById("id").getTextContent();\nassertThat(id).isEqualTo("123");\nString summary = newMessagePage.getHtmlElementById("summary").getTextContent();\nassertThat(summary).isEqualTo("Spring Rocks");\nString text = newMessagePage.getHtmlElementById("text").getTextContent();\nassertThat(text).isEqualTo("In case you didn\'t know, Spring Rocks!");\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('assertThat(newMessagePage.getUrl().toString()).endsWith("/messages/123")\nval id = newMessagePage.getHtmlElementById("id").getTextContent()\nassertThat(id).isEqualTo("123")\nval summary = newMessagePage.getHtmlElementById("summary").getTextContent()\nassertThat(summary).isEqualTo("Spring Rocks")\nval text = newMessagePage.getHtmlElementById("text").getTextContent()\nassertThat(text).isEqualTo("In case you didn\'t know, Spring Rocks!")\n')])])]),n("p",[e._v("The preceding code improves on our"),n("a",{attrs:{href:"#spring-mvc-test-server-htmlunit-mock-mvc-test"}},[e._v("MockMvc test")]),e._v(" in a number of ways.\nFirst, we no longer have to explicitly verify our form and then create a request that\nlooks like the form. Instead, we request the form, fill it out, and submit it, thereby\nsignificantly reducing the overhead.")]),e._v(" "),n("p",[e._v("Another important factor is that "),n("a",{attrs:{href:"http://htmlunit.sourceforge.net/javascript.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("HtmlUnit\nuses the Mozilla Rhino engine"),n("OutboundLink")],1),e._v(" to evaluate JavaScript. This means that we can also test\nthe behavior of JavaScript within our pages.")]),e._v(" "),n("p",[e._v("See the "),n("a",{attrs:{href:"http://htmlunit.sourceforge.net/gettingStarted.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("HtmlUnit documentation"),n("OutboundLink")],1),e._v(" for\nadditional information about using HtmlUnit.")]),e._v(" "),n("h6",{attrs:{id:"advanced-mockmvcwebclientbuilder"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#advanced-mockmvcwebclientbuilder"}},[e._v("#")]),e._v(" Advanced "),n("code",[e._v("MockMvcWebClientBuilder")])]),e._v(" "),n("p",[e._v("In the examples so far, we have used "),n("code",[e._v("MockMvcWebClientBuilder")]),e._v(" in the simplest way\npossible, by building a "),n("code",[e._v("WebClient")]),e._v(" based on the "),n("code",[e._v("WebApplicationContext")]),e._v(" loaded for us by\nthe Spring TestContext Framework. This approach is repeated in the following example:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("WebClient webClient;\n\n@BeforeEach\nvoid setup(WebApplicationContext context) {\n webClient = MockMvcWebClientBuilder\n .webAppContextSetup(context)\n .build();\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("lateinit var webClient: WebClient\n\n@BeforeEach\nfun setup(context: WebApplicationContext) {\n webClient = MockMvcWebClientBuilder\n .webAppContextSetup(context)\n .build()\n}\n")])])]),n("p",[e._v("We can also specify additional configuration options, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('WebClient webClient;\n\n@BeforeEach\nvoid setup() {\n webClient = MockMvcWebClientBuilder\n // demonstrates applying a MockMvcConfigurer (Spring Security)\n .webAppContextSetup(context, springSecurity())\n // for illustration only - defaults to ""\n .contextPath("")\n // By default MockMvc is used for localhost only;\n // the following will use MockMvc for example.com and example.org as well\n .useMockMvcForHosts("example.com","example.org")\n .build();\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('lateinit var webClient: WebClient\n\n@BeforeEach\nfun setup() {\n webClient = MockMvcWebClientBuilder\n // demonstrates applying a MockMvcConfigurer (Spring Security)\n .webAppContextSetup(context, springSecurity())\n // for illustration only - defaults to ""\n .contextPath("")\n // By default MockMvc is used for localhost only;\n // the following will use MockMvc for example.com and example.org as well\n .useMockMvcForHosts("example.com","example.org")\n .build()\n}\n')])])]),n("p",[e._v("As an alternative, we can perform the exact same setup by configuring the "),n("code",[e._v("MockMvc")]),e._v("instance separately and supplying it to the "),n("code",[e._v("MockMvcWebClientBuilder")]),e._v(", as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('MockMvc mockMvc = MockMvcBuilders\n .webAppContextSetup(context)\n .apply(springSecurity())\n .build();\n\nwebClient = MockMvcWebClientBuilder\n .mockMvcSetup(mockMvc)\n // for illustration only - defaults to ""\n .contextPath("")\n // By default MockMvc is used for localhost only;\n // the following will use MockMvc for example.com and example.org as well\n .useMockMvcForHosts("example.com","example.org")\n .build();\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed\n")])])]),n("p",[e._v("This is more verbose, but, by building the "),n("code",[e._v("WebClient")]),e._v(" with a "),n("code",[e._v("MockMvc")]),e._v(" instance, we have\nthe full power of MockMvc at our fingertips.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("For additional information on creating a "),n("code",[e._v("MockMvc")]),e._v(" instance, see"),n("a",{attrs:{href:"#spring-mvc-test-server-setup-options"}},[e._v("Setup Choices")]),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"mockmvc-and-webdriver"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#mockmvc-and-webdriver"}},[e._v("#")]),e._v(" MockMvc and WebDriver")]),e._v(" "),n("p",[e._v("In the previous sections, we have seen how to use MockMvc in conjunction with the raw\nHtmlUnit APIs. In this section, we use additional abstractions within the Selenium"),n("a",{attrs:{href:"https://docs.seleniumhq.org/projects/webdriver/",target:"_blank",rel:"noopener noreferrer"}},[e._v("WebDriver"),n("OutboundLink")],1),e._v(" to make things even easier.")]),e._v(" "),n("h6",{attrs:{id:"why-webdriver-and-mockmvc"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#why-webdriver-and-mockmvc"}},[e._v("#")]),e._v(" Why WebDriver and MockMvc?")]),e._v(" "),n("p",[e._v("We can already use HtmlUnit and MockMvc, so why would we want to use WebDriver? The\nSelenium WebDriver provides a very elegant API that lets us easily organize our code. To\nbetter show how it works, we explore an example in this section.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("Despite being a part of "),n("a",{attrs:{href:"https://docs.seleniumhq.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Selenium"),n("OutboundLink")],1),e._v(", WebDriver does not"),n("br"),e._v("require a Selenium Server to run your tests.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Suppose we need to ensure that a message is created properly. The tests involve finding\nthe HTML form input elements, filling them out, and making various assertions.")]),e._v(" "),n("p",[e._v("This approach results in numerous separate tests because we want to test error conditions\nas well. For example, we want to ensure that we get an error if we fill out only part of\nthe form. If we fill out the entire form, the newly created message should be displayed\nafterwards.")]),e._v(" "),n("p",[e._v("If one of the fields were named “summary”, we might have something that resembles the\nfollowing repeated in multiple places within our tests:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('HtmlTextInput summaryInput = currentPage.getHtmlElementById("summary");\nsummaryInput.setValueAttribute(summary);\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('val summaryInput = currentPage.getHtmlElementById("summary")\nsummaryInput.setValueAttribute(summary)\n')])])]),n("p",[e._v("So what happens if we change the "),n("code",[e._v("id")]),e._v(" to "),n("code",[e._v("smmry")]),e._v("? Doing so would force us to update all\nof our tests to incorporate this change. This violates the DRY principle, so we should\nideally extract this code into its own method, as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('public HtmlPage createMessage(HtmlPage currentPage, String summary, String text) {\n setSummary(currentPage, summary);\n // ...\n}\n\npublic void setSummary(HtmlPage currentPage, String summary) {\n HtmlTextInput summaryInput = currentPage.getHtmlElementById("summary");\n summaryInput.setValueAttribute(summary);\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('fun createMessage(currentPage: HtmlPage, summary:String, text:String) :HtmlPage{\n setSummary(currentPage, summary);\n // ...\n}\n\nfun setSummary(currentPage:HtmlPage , summary: String) {\n val summaryInput = currentPage.getHtmlElementById("summary")\n summaryInput.setValueAttribute(summary)\n}\n')])])]),n("p",[e._v("Doing so ensures that we do not have to update all of our tests if we change the UI.")]),e._v(" "),n("p",[e._v("We might even take this a step further and place this logic within an "),n("code",[e._v("Object")]),e._v(" that\nrepresents the "),n("code",[e._v("HtmlPage")]),e._v(" we are currently on, as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('public class CreateMessagePage {\n\n final HtmlPage currentPage;\n\n final HtmlTextInput summaryInput;\n\n final HtmlSubmitInput submit;\n\n public CreateMessagePage(HtmlPage currentPage) {\n this.currentPage = currentPage;\n this.summaryInput = currentPage.getHtmlElementById("summary");\n this.submit = currentPage.getHtmlElementById("submit");\n }\n\n public T createMessage(String summary, String text) throws Exception {\n setSummary(summary);\n\n HtmlPage result = submit.click();\n boolean error = CreateMessagePage.at(result);\n\n return (T) (error ? new CreateMessagePage(result) : new ViewMessagePage(result));\n }\n\n public void setSummary(String summary) throws Exception {\n summaryInput.setValueAttribute(summary);\n }\n\n public static boolean at(HtmlPage page) {\n return "Create Message".equals(page.getTitleText());\n }\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v(' class CreateMessagePage(private val currentPage: HtmlPage) {\n\n val summaryInput: HtmlTextInput = currentPage.getHtmlElementById("summary")\n\n val submit: HtmlSubmitInput = currentPage.getHtmlElementById("submit")\n\n fun createMessage(summary: String, text: String): T {\n setSummary(summary)\n\n val result = submit.click()\n val error = at(result)\n\n return (if (error) CreateMessagePage(result) else ViewMessagePage(result)) as T\n }\n\n fun setSummary(summary: String) {\n summaryInput.setValueAttribute(summary)\n }\n\n fun at(page: HtmlPage): Boolean {\n return "Create Message" == page.getTitleText()\n }\n }\n}\n')])])]),n("p",[e._v("Formerly, this pattern was known as the"),n("a",{attrs:{href:"https://github.com/SeleniumHQ/selenium/wiki/PageObjects",target:"_blank",rel:"noopener noreferrer"}},[e._v("Page Object Pattern"),n("OutboundLink")],1),e._v(". While we\ncan certainly do this with HtmlUnit, WebDriver provides some tools that we explore in the\nfollowing sections to make this pattern much easier to implement.")]),e._v(" "),n("h6",{attrs:{id:"mockmvc-and-webdriver-setup"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#mockmvc-and-webdriver-setup"}},[e._v("#")]),e._v(" MockMvc and WebDriver Setup")]),e._v(" "),n("p",[e._v("To use Selenium WebDriver with the Spring MVC Test framework, make sure that your project\nincludes a test dependency on "),n("code",[e._v("org.seleniumhq.selenium:selenium-htmlunit-driver")]),e._v(".")]),e._v(" "),n("p",[e._v("We can easily create a Selenium WebDriver that integrates with MockMvc by using the"),n("code",[e._v("MockMvcHtmlUnitDriverBuilder")]),e._v(" as the following example shows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("WebDriver driver;\n\n@BeforeEach\nvoid setup(WebApplicationContext context) {\n driver = MockMvcHtmlUnitDriverBuilder\n .webAppContextSetup(context)\n .build();\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("lateinit var driver: WebDriver\n\n@BeforeEach\nfun setup(context: WebApplicationContext) {\n driver = MockMvcHtmlUnitDriverBuilder\n .webAppContextSetup(context)\n .build()\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("This is a simple example of using "),n("code",[e._v("MockMvcHtmlUnitDriverBuilder")]),e._v(". For more advanced"),n("br"),e._v("usage, see "),n("a",{attrs:{href:"#spring-mvc-test-server-htmlunit-webdriver-advanced-builder"}},[e._v("Advanced "),n("code",[e._v("MockMvcHtmlUnitDriverBuilder")])]),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("The preceding example ensures that any URL that references "),n("code",[e._v("localhost")]),e._v(" as the server is\ndirected to our "),n("code",[e._v("MockMvc")]),e._v(" instance without the need for a real HTTP connection. Any other\nURL is requested by using a network connection, as normal. This lets us easily test the\nuse of CDNs.")]),e._v(" "),n("h6",{attrs:{id:"mockmvc-and-webdriver-usage"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#mockmvc-and-webdriver-usage"}},[e._v("#")]),e._v(" MockMvc and WebDriver Usage")]),e._v(" "),n("p",[e._v("Now we can use WebDriver as we normally would but without the need to deploy our\napplication to a Servlet container. For example, we can request the view to create a\nmessage with the following:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("CreateMessagePage page = CreateMessagePage.to(driver);\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("val page = CreateMessagePage.to(driver)\n")])])]),n("p",[e._v("We can then fill out the form and submit it to create a message, as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("ViewMessagePage viewMessagePage =\n page.createMessage(ViewMessagePage.class, expectedSummary, expectedText);\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("val viewMessagePage =\n page.createMessage(ViewMessagePage::class, expectedSummary, expectedText)\n")])])]),n("p",[e._v("This improves on the design of our "),n("a",{attrs:{href:"#spring-mvc-test-server-htmlunit-mah-usage"}},[e._v("HtmlUnit test")]),e._v("by leveraging the Page Object Pattern. As we mentioned in"),n("a",{attrs:{href:"#spring-mvc-test-server-htmlunit-webdriver-why"}},[e._v("Why WebDriver and MockMvc?")]),e._v(", we can use the Page Object Pattern\nwith HtmlUnit, but it is much easier with WebDriver. Consider the following"),n("code",[e._v("CreateMessagePage")]),e._v(" implementation:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('public class CreateMessagePage\n extends AbstractPage { (1)\n\n (2)\n private WebElement summary;\n private WebElement text;\n\n (3)\n @FindBy(css = "input[type=submit]")\n private WebElement submit;\n\n public CreateMessagePage(WebDriver driver) {\n super(driver);\n }\n\n public T createMessage(Class resultPage, String summary, String details) {\n this.summary.sendKeys(summary);\n this.text.sendKeys(details);\n this.submit.click();\n return PageFactory.initElements(driver, resultPage);\n }\n\n public static CreateMessagePage to(WebDriver driver) {\n driver.get("http://localhost:9990/mail/messages/form");\n return PageFactory.initElements(driver, CreateMessagePage.class);\n }\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[n("code",[e._v("CreateMessagePage")]),e._v(" extends the "),n("code",[e._v("AbstractPage")]),e._v(". We do not go over the details of"),n("code",[e._v("AbstractPage")]),e._v(", but, in summary, it contains common functionality for all of our pages."),n("br"),e._v("For example, if our application has a navigational bar, global error messages, and other"),n("br"),e._v("features, we can place this logic in a shared location.")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("We have a member variable for each of the parts of the HTML page in which we are"),n("br"),e._v("interested. These are of type "),n("code",[e._v("WebElement")]),e._v(". WebDriver’s"),n("a",{attrs:{href:"https://github.com/SeleniumHQ/selenium/wiki/PageFactory",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("PageFactory")]),n("OutboundLink")],1),e._v(" lets us remove a"),n("br"),e._v("lot of code from the HtmlUnit version of "),n("code",[e._v("CreateMessagePage")]),e._v(" by automatically resolving"),n("br"),e._v("each "),n("code",[e._v("WebElement")]),e._v(". The"),n("a",{attrs:{href:"https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/PageFactory.html#initElements-org.openqa.selenium.WebDriver-java.lang.Class-",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("PageFactory#initElements(WebDriver,Class)")]),n("OutboundLink")],1),e._v("method automatically resolves each "),n("code",[e._v("WebElement")]),e._v(" by using the field name and looking it up"),n("br"),e._v("by the "),n("code",[e._v("id")]),e._v(" or "),n("code",[e._v("name")]),e._v(" of the element within the HTML page.")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("3")])]),e._v(" "),n("td",[e._v("We can use the"),n("a",{attrs:{href:"https://github.com/SeleniumHQ/selenium/wiki/PageFactory#making-the-example-work-using-annotations",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@FindBy")]),e._v(" annotation"),n("OutboundLink")],1),e._v("to override the default lookup behavior. Our example shows how to use the "),n("code",[e._v("@FindBy")]),e._v("annotation to look up our submit button with a "),n("code",[e._v("css")]),e._v(" selector ("),n("strong",[e._v("input[type=submit]")]),e._v(").")])])])]),e._v(" "),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('class CreateMessagePage(private val driver: WebDriver) : AbstractPage(driver) { (1)\n\n (2)\n private lateinit var summary: WebElement\n private lateinit var text: WebElement\n\n (3)\n @FindBy(css = "input[type=submit]")\n private lateinit var submit: WebElement\n\n fun createMessage(resultPage: Class, summary: String, details: String): T {\n this.summary.sendKeys(summary)\n text.sendKeys(details)\n submit.click()\n return PageFactory.initElements(driver, resultPage)\n }\n companion object {\n fun to(driver: WebDriver): CreateMessagePage {\n driver.get("http://localhost:9990/mail/messages/form")\n return PageFactory.initElements(driver, CreateMessagePage::class.java)\n }\n }\n}\n')])])]),n("table",[n("thead",[n("tr",[n("th",[n("strong",[e._v("1")])]),e._v(" "),n("th",[n("code",[e._v("CreateMessagePage")]),e._v(" extends the "),n("code",[e._v("AbstractPage")]),e._v(". We do not go over the details of"),n("code",[e._v("AbstractPage")]),e._v(", but, in summary, it contains common functionality for all of our pages."),n("br"),e._v("For example, if our application has a navigational bar, global error messages, and other"),n("br"),e._v("features, we can place this logic in a shared location.")])])]),e._v(" "),n("tbody",[n("tr",[n("td",[n("strong",[e._v("2")])]),e._v(" "),n("td",[e._v("We have a member variable for each of the parts of the HTML page in which we are"),n("br"),e._v("interested. These are of type "),n("code",[e._v("WebElement")]),e._v(". WebDriver’s"),n("a",{attrs:{href:"https://github.com/SeleniumHQ/selenium/wiki/PageFactory",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("PageFactory")]),n("OutboundLink")],1),e._v(" lets us remove a"),n("br"),e._v("lot of code from the HtmlUnit version of "),n("code",[e._v("CreateMessagePage")]),e._v(" by automatically resolving"),n("br"),e._v("each "),n("code",[e._v("WebElement")]),e._v(". The"),n("a",{attrs:{href:"https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/PageFactory.html#initElements-org.openqa.selenium.WebDriver-java.lang.Class-",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("PageFactory#initElements(WebDriver,Class)")]),n("OutboundLink")],1),e._v("method automatically resolves each "),n("code",[e._v("WebElement")]),e._v(" by using the field name and looking it up"),n("br"),e._v("by the "),n("code",[e._v("id")]),e._v(" or "),n("code",[e._v("name")]),e._v(" of the element within the HTML page.")])]),e._v(" "),n("tr",[n("td",[n("strong",[e._v("3")])]),e._v(" "),n("td",[e._v("We can use the"),n("a",{attrs:{href:"https://github.com/SeleniumHQ/selenium/wiki/PageFactory#making-the-example-work-using-annotations",target:"_blank",rel:"noopener noreferrer"}},[n("code",[e._v("@FindBy")]),e._v(" annotation"),n("OutboundLink")],1),e._v("to override the default lookup behavior. Our example shows how to use the "),n("code",[e._v("@FindBy")]),e._v("annotation to look up our submit button with a "),n("code",[e._v("css")]),e._v(" selector ("),n("strong",[e._v("input[type=submit]")]),e._v(").")])])])]),e._v(" "),n("p",[e._v("Finally, we can verify that a new message was created successfully. The following\nassertions use the "),n("a",{attrs:{href:"https://assertj.github.io/doc/",target:"_blank",rel:"noopener noreferrer"}},[e._v("AssertJ"),n("OutboundLink")],1),e._v(" assertion library:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('assertThat(viewMessagePage.getMessage()).isEqualTo(expectedMessage);\nassertThat(viewMessagePage.getSuccess()).isEqualTo("Successfully created a new message");\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('assertThat(viewMessagePage.message).isEqualTo(expectedMessage)\nassertThat(viewMessagePage.success).isEqualTo("Successfully created a new message")\n')])])]),n("p",[e._v("We can see that our "),n("code",[e._v("ViewMessagePage")]),e._v(" lets us interact with our custom domain model. For\nexample, it exposes a method that returns a "),n("code",[e._v("Message")]),e._v(" object:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("public Message getMessage() throws ParseException {\n Message message = new Message();\n message.setId(getId());\n message.setCreated(getCreated());\n message.setSummary(getSummary());\n message.setText(getText());\n return message;\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("fun getMessage() = Message(getId(), getCreated(), getSummary(), getText())\n")])])]),n("p",[e._v("We can then use the rich domain objects in our assertions.")]),e._v(" "),n("p",[e._v("Lastly, we must not forget to close the "),n("code",[e._v("WebDriver")]),e._v(" instance when the test is complete,\nas follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@AfterEach\nvoid destroy() {\n if (driver != null) {\n driver.close();\n }\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("@AfterEach\nfun destroy() {\n if (driver != null) {\n driver.close()\n }\n}\n")])])]),n("p",[e._v("For additional information on using WebDriver, see the Selenium"),n("a",{attrs:{href:"https://github.com/SeleniumHQ/selenium/wiki/Getting-Started",target:"_blank",rel:"noopener noreferrer"}},[e._v("WebDriver documentation"),n("OutboundLink")],1),e._v(".")]),e._v(" "),n("h6",{attrs:{id:"advanced-mockmvchtmlunitdriverbuilder"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#advanced-mockmvchtmlunitdriverbuilder"}},[e._v("#")]),e._v(" Advanced "),n("code",[e._v("MockMvcHtmlUnitDriverBuilder")])]),e._v(" "),n("p",[e._v("In the examples so far, we have used "),n("code",[e._v("MockMvcHtmlUnitDriverBuilder")]),e._v(" in the simplest way\npossible, by building a "),n("code",[e._v("WebDriver")]),e._v(" based on the "),n("code",[e._v("WebApplicationContext")]),e._v(" loaded for us by\nthe Spring TestContext Framework. This approach is repeated here, as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("WebDriver driver;\n\n@BeforeEach\nvoid setup(WebApplicationContext context) {\n driver = MockMvcHtmlUnitDriverBuilder\n .webAppContextSetup(context)\n .build();\n}\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("lateinit var driver: WebDriver\n\n@BeforeEach\nfun setup(context: WebApplicationContext) {\n driver = MockMvcHtmlUnitDriverBuilder\n .webAppContextSetup(context)\n .build()\n}\n")])])]),n("p",[e._v("We can also specify additional configuration options, as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('WebDriver driver;\n\n@BeforeEach\nvoid setup() {\n driver = MockMvcHtmlUnitDriverBuilder\n // demonstrates applying a MockMvcConfigurer (Spring Security)\n .webAppContextSetup(context, springSecurity())\n // for illustration only - defaults to ""\n .contextPath("")\n // By default MockMvc is used for localhost only;\n // the following will use MockMvc for example.com and example.org as well\n .useMockMvcForHosts("example.com","example.org")\n .build();\n}\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('lateinit var driver: WebDriver\n\n@BeforeEach\nfun setup() {\n driver = MockMvcHtmlUnitDriverBuilder\n // demonstrates applying a MockMvcConfigurer (Spring Security)\n .webAppContextSetup(context, springSecurity())\n // for illustration only - defaults to ""\n .contextPath("")\n // By default MockMvc is used for localhost only;\n // the following will use MockMvc for example.com and example.org as well\n .useMockMvcForHosts("example.com","example.org")\n .build()\n}\n')])])]),n("p",[e._v("As an alternative, we can perform the exact same setup by configuring the "),n("code",[e._v("MockMvc")]),e._v("instance separately and supplying it to the "),n("code",[e._v("MockMvcHtmlUnitDriverBuilder")]),e._v(", as follows:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('MockMvc mockMvc = MockMvcBuilders\n .webAppContextSetup(context)\n .apply(springSecurity())\n .build();\n\ndriver = MockMvcHtmlUnitDriverBuilder\n .mockMvcSetup(mockMvc)\n // for illustration only - defaults to ""\n .contextPath("")\n // By default MockMvc is used for localhost only;\n // the following will use MockMvc for example.com and example.org as well\n .useMockMvcForHosts("example.com","example.org")\n .build();\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("// Not possible in Kotlin until https://youtrack.jetbrains.com/issue/KT-22208 is fixed\n")])])]),n("p",[e._v("This is more verbose, but, by building the "),n("code",[e._v("WebDriver")]),e._v(" with a "),n("code",[e._v("MockMvc")]),e._v(" instance, we have\nthe full power of MockMvc at our fingertips.")]),e._v(" "),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("For additional information on creating a "),n("code",[e._v("MockMvc")]),e._v(" instance, see"),n("a",{attrs:{href:"#spring-mvc-test-server-setup-options"}},[e._v("Setup Choices")]),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("h5",{attrs:{id:"mockmvc-and-geb"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#mockmvc-and-geb"}},[e._v("#")]),e._v(" MockMvc and Geb")]),e._v(" "),n("p",[e._v("In the previous section, we saw how to use MockMvc with WebDriver. In this section, we\nuse "),n("a",{attrs:{href:"http://www.gebish.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Geb"),n("OutboundLink")],1),e._v(" to make our tests even Groovy-er.")]),e._v(" "),n("h6",{attrs:{id:"why-geb-and-mockmvc"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#why-geb-and-mockmvc"}},[e._v("#")]),e._v(" Why Geb and MockMvc?")]),e._v(" "),n("p",[e._v("Geb is backed by WebDriver, so it offers many of the"),n("a",{attrs:{href:"#spring-mvc-test-server-htmlunit-webdriver-why"}},[e._v("same benefits")]),e._v(" that we get from\nWebDriver. However, Geb makes things even easier by taking care of some of the\nboilerplate code for us.")]),e._v(" "),n("h6",{attrs:{id:"mockmvc-and-geb-setup"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#mockmvc-and-geb-setup"}},[e._v("#")]),e._v(" MockMvc and Geb Setup")]),e._v(" "),n("p",[e._v("We can easily initialize a Geb "),n("code",[e._v("Browser")]),e._v(" with a Selenium WebDriver that uses MockMvc, as\nfollows:")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("def setup() {\n browser.driver = MockMvcHtmlUnitDriverBuilder\n .webAppContextSetup(context)\n .build()\n}\n")])])]),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("This is a simple example of using "),n("code",[e._v("MockMvcHtmlUnitDriverBuilder")]),e._v(". For more advanced"),n("br"),e._v("usage, see "),n("a",{attrs:{href:"#spring-mvc-test-server-htmlunit-webdriver-advanced-builder"}},[e._v("Advanced "),n("code",[e._v("MockMvcHtmlUnitDriverBuilder")])]),e._v(".")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("This ensures that any URL referencing "),n("code",[e._v("localhost")]),e._v(" as the server is directed to our"),n("code",[e._v("MockMvc")]),e._v(" instance without the need for a real HTTP connection. Any other URL is\nrequested by using a network connection as normal. This lets us easily test the use of\nCDNs.")]),e._v(" "),n("h6",{attrs:{id:"mockmvc-and-geb-usage"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#mockmvc-and-geb-usage"}},[e._v("#")]),e._v(" MockMvc and Geb Usage")]),e._v(" "),n("p",[e._v("Now we can use Geb as we normally would but without the need to deploy our application to\na Servlet container. For example, we can request the view to create a message with the\nfollowing:")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("to CreateMessagePage\n")])])]),n("p",[e._v("We can then fill out the form and submit it to create a message, as follows:")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("when:\nform.summary = expectedSummary\nform.text = expectedMessage\nsubmit.click(ViewMessagePage)\n")])])]),n("p",[e._v("Any unrecognized method calls or property accesses or references that are not found are\nforwarded to the current page object. This removes a lot of the boilerplate code we\nneeded when using WebDriver directly.")]),e._v(" "),n("p",[e._v("As with direct WebDriver usage, this improves on the design of our"),n("a",{attrs:{href:"#spring-mvc-test-server-htmlunit-mah-usage"}},[e._v("HtmlUnit test")]),e._v(" by using the Page Object\nPattern. As mentioned previously, we can use the Page Object Pattern with HtmlUnit and\nWebDriver, but it is even easier with Geb. Consider our new Groovy-based"),n("code",[e._v("CreateMessagePage")]),e._v(" implementation:")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("class CreateMessagePage extends Page {\n static url = 'messages/form'\n static at = { assert title == 'Messages : Create'; true }\n static content = {\n submit { $('input[type=submit]') }\n form { $('form') }\n errors(required:false) { $('label.error, .alert-error')?.text() }\n }\n}\n")])])]),n("p",[e._v("Our "),n("code",[e._v("CreateMessagePage")]),e._v(" extends "),n("code",[e._v("Page")]),e._v(". We do not go over the details of "),n("code",[e._v("Page")]),e._v(", but, in\nsummary, it contains common functionality for all of our pages. We define a URL in which\nthis page can be found. This lets us navigate to the page, as follows:")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("to CreateMessagePage\n")])])]),n("p",[e._v("We also have an "),n("code",[e._v("at")]),e._v(" closure that determines if we are at the specified page. It should\nreturn "),n("code",[e._v("true")]),e._v(" if we are on the correct page. This is why we can assert that we are on the\ncorrect page, as follows:")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("then:\nat CreateMessagePage\nerrors.contains('This field is required.')\n")])])]),n("table",[n("thead",[n("tr",[n("th"),e._v(" "),n("th",[e._v("We use an assertion in the closure so that we can determine where things went wrong"),n("br"),e._v("if we were at the wrong page.")])])]),e._v(" "),n("tbody")]),e._v(" "),n("p",[e._v("Next, we create a "),n("code",[e._v("content")]),e._v(" closure that specifies all the areas of interest within the\npage. We can use a"),n("a",{attrs:{href:"http://www.gebish.org/manual/current/#the-jquery-ish-navigator-api",target:"_blank",rel:"noopener noreferrer"}},[e._v("jQuery-ish Navigator\nAPI"),n("OutboundLink")],1),e._v(" to select the content in which we are interested.")]),e._v(" "),n("p",[e._v("Finally, we can verify that a new message was created successfully, as follows:")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("then:\nat ViewMessagePage\nsuccess == 'Successfully created a new message'\nid\ndate\nsummary == expectedSummary\nmessage == expectedMessage\n")])])]),n("p",[e._v("For further details on how to get the most out of Geb, see"),n("a",{attrs:{href:"http://www.gebish.org/manual/current/",target:"_blank",rel:"noopener noreferrer"}},[e._v("The Book of Geb"),n("OutboundLink")],1),e._v(" user’s manual.")]),e._v(" "),n("h3",{attrs:{id:"_3-8-testing-client-applications"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-8-testing-client-applications"}},[e._v("#")]),e._v(" 3.8. Testing Client Applications")]),e._v(" "),n("p",[e._v("You can use client-side tests to test code that internally uses the "),n("code",[e._v("RestTemplate")]),e._v(". The\nidea is to declare expected requests and to provide “stub” responses so that you can\nfocus on testing the code in isolation (that is, without running a server). The following\nexample shows how to do so:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('RestTemplate restTemplate = new RestTemplate();\n\nMockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();\nmockServer.expect(requestTo("/greeting")).andRespond(withSuccess());\n\n// Test code that uses the above RestTemplate ...\n\nmockServer.verify();\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('val restTemplate = RestTemplate()\n\nval mockServer = MockRestServiceServer.bindTo(restTemplate).build()\nmockServer.expect(requestTo("/greeting")).andRespond(withSuccess())\n\n// Test code that uses the above RestTemplate ...\n\nmockServer.verify()\n')])])]),n("p",[e._v("In the preceding example, "),n("code",[e._v("MockRestServiceServer")]),e._v(" (the central class for client-side REST\ntests) configures the "),n("code",[e._v("RestTemplate")]),e._v(" with a custom "),n("code",[e._v("ClientHttpRequestFactory")]),e._v(" that\nasserts actual requests against expectations and returns “stub” responses. In this\ncase, we expect a request to "),n("code",[e._v("/greeting")]),e._v(" and want to return a 200 response with"),n("code",[e._v("text/plain")]),e._v(" content. We can define additional expected requests and stub responses as\nneeded. When we define expected requests and stub responses, the "),n("code",[e._v("RestTemplate")]),e._v(" can be\nused in client-side code as usual. At the end of testing, "),n("code",[e._v("mockServer.verify()")]),e._v(" can be\nused to verify that all expectations have been satisfied.")]),e._v(" "),n("p",[e._v("By default, requests are expected in the order in which expectations were declared. You\ncan set the "),n("code",[e._v("ignoreExpectOrder")]),e._v(" option when building the server, in which case all\nexpectations are checked (in order) to find a match for a given request. That means\nrequests are allowed to come in any order. The following example uses "),n("code",[e._v("ignoreExpectOrder")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("server = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build();\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("server = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build()\n")])])]),n("p",[e._v("Even with unordered requests by default, each request is allowed to run once only.\nThe "),n("code",[e._v("expect")]),e._v(" method provides an overloaded variant that accepts an "),n("code",[e._v("ExpectedCount")]),e._v("argument that specifies a count range (for example, "),n("code",[e._v("once")]),e._v(", "),n("code",[e._v("manyTimes")]),e._v(", "),n("code",[e._v("max")]),e._v(", "),n("code",[e._v("min")]),e._v(","),n("code",[e._v("between")]),e._v(", and so on). The following example uses "),n("code",[e._v("times")]),e._v(":")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('RestTemplate restTemplate = new RestTemplate();\n\nMockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();\nmockServer.expect(times(2), requestTo("/something")).andRespond(withSuccess());\nmockServer.expect(times(3), requestTo("/somewhere")).andRespond(withSuccess());\n\n// ...\n\nmockServer.verify();\n')])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v('val restTemplate = RestTemplate()\n\nval mockServer = MockRestServiceServer.bindTo(restTemplate).build()\nmockServer.expect(times(2), requestTo("/something")).andRespond(withSuccess())\nmockServer.expect(times(3), requestTo("/somewhere")).andRespond(withSuccess())\n\n// ...\n\nmockServer.verify()\n')])])]),n("p",[e._v("Note that, when "),n("code",[e._v("ignoreExpectOrder")]),e._v(' is not set (the default), and, therefore, requests\nare expected in order of declaration, then that order applies only to the first of any\nexpected request. For example if "/something" is expected two times followed by\n"/somewhere" three times, then there should be a request to "/something" before there is\na request to "/somewhere", but, aside from that subsequent "/something" and "/somewhere",\nrequests can come at any time.')]),e._v(" "),n("p",[e._v("As an alternative to all of the above, the client-side test support also provides a"),n("code",[e._v("ClientHttpRequestFactory")]),e._v(" implementation that you can configure into a "),n("code",[e._v("RestTemplate")]),e._v(" to\nbind it to a "),n("code",[e._v("MockMvc")]),e._v(" instance. That allows processing requests using actual server-side\nlogic but without running a server. The following example shows how to do so:")]),e._v(" "),n("p",[e._v("Java")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();\nthis.restTemplate = new RestTemplate(new MockMvcClientHttpRequestFactory(mockMvc));\n\n// Test code that uses the above RestTemplate ...\n")])])]),n("p",[e._v("Kotlin")]),e._v(" "),n("div",{staticClass:"language- extra-class"},[n("pre",{pre:!0,attrs:{class:"language-text"}},[n("code",[e._v("val mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build()\nrestTemplate = RestTemplate(MockMvcClientHttpRequestFactory(mockMvc))\n\n// Test code that uses the above RestTemplate ...\n")])])]),n("h4",{attrs:{id:"_3-8-1-static-imports"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-8-1-static-imports"}},[e._v("#")]),e._v(" 3.8.1. Static Imports")]),e._v(" "),n("p",[e._v("As with server-side tests, the fluent API for client-side tests requires a few static\nimports. Those are easy to find by searching for "),n("code",[e._v("MockRest*")]),e._v(". Eclipse users should add"),n("code",[e._v("MockRestRequestMatchers.*")]),e._v(" and "),n("code",[e._v("MockRestResponseCreators.*")]),e._v(" as\n“favorite static members” in the Eclipse preferences under Java → Editor → Content\nAssist → Favorites. That allows using content assist after typing the first character of\nthe static method name. Other IDEs (such IntelliJ) may not require any additional\nconfiguration. Check for the support for code completion on static members.")]),e._v(" "),n("h4",{attrs:{id:"_3-8-2-further-examples-of-client-side-rest-tests"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-8-2-further-examples-of-client-side-rest-tests"}},[e._v("#")]),e._v(" 3.8.2. Further Examples of Client-side REST Tests")]),e._v(" "),n("p",[e._v("Spring MVC Test’s own tests include"),n("a",{attrs:{href:"https://github.com/spring-projects/spring-framework/tree/main/spring-test/src/test/java/org/springframework/test/web/client/samples",target:"_blank",rel:"noopener noreferrer"}},[e._v("example\ntests"),n("OutboundLink")],1),e._v(" of client-side REST tests.")]),e._v(" "),n("h2",{attrs:{id:"_4-further-resources"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_4-further-resources"}},[e._v("#")]),e._v(" 4. Further Resources")]),e._v(" "),n("p",[e._v("See the following resources for more information about testing:")]),e._v(" "),n("ul",[n("li",[n("p",[n("a",{attrs:{href:"https://www.junit.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("JUnit"),n("OutboundLink")],1),e._v(": “A programmer-friendly testing framework for Java”.\nUsed by the Spring Framework in its test suite and supported in the"),n("a",{attrs:{href:"#testcontext-framework"}},[e._v("Spring TestContext Framework")]),e._v(".")])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"https://testng.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("TestNG"),n("OutboundLink")],1),e._v(": A testing framework inspired by JUnit with added support\nfor test groups, data-driven testing, distributed testing, and other features. Supported\nin the "),n("a",{attrs:{href:"#testcontext-framework"}},[e._v("Spring TestContext Framework")])])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"https://assertj.github.io/doc/",target:"_blank",rel:"noopener noreferrer"}},[e._v("AssertJ"),n("OutboundLink")],1),e._v(": “Fluent assertions for Java”,\nincluding support for Java 8 lambdas, streams, and other features.")])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"https://en.wikipedia.org/wiki/Mock_Object",target:"_blank",rel:"noopener noreferrer"}},[e._v("Mock Objects"),n("OutboundLink")],1),e._v(": Article in Wikipedia.")])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"http://www.mockobjects.com/",target:"_blank",rel:"noopener noreferrer"}},[e._v("MockObjects.com"),n("OutboundLink")],1),e._v(": Web site dedicated to mock objects, a\ntechnique for improving the design of code within test-driven development.")])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"https://mockito.github.io",target:"_blank",rel:"noopener noreferrer"}},[e._v("Mockito"),n("OutboundLink")],1),e._v(": Java mock library based on the"),n("a",{attrs:{href:"http://xunitpatterns.com/Test%20Spy.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("Test Spy"),n("OutboundLink")],1),e._v(" pattern. Used by the Spring Framework\nin its test suite.")])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"https://easymock.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("EasyMock"),n("OutboundLink")],1),e._v(": Java library “that provides Mock Objects for\ninterfaces (and objects through the class extension) by generating them on the fly using\nJava’s proxy mechanism.”")])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"https://jmock.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("JMock"),n("OutboundLink")],1),e._v(": Library that supports test-driven development of Java code\nwith mock objects.")])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"https://www.dbunit.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("DbUnit"),n("OutboundLink")],1),e._v(": JUnit extension (also usable with Ant and Maven) that\nis targeted at database-driven projects and, among other things, puts your database into\na known state between test runs.")])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"https://www.testcontainers.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Testcontainers"),n("OutboundLink")],1),e._v(": Java library that supports JUnit\ntests, providing lightweight, throwaway instances of common databases, Selenium web\nbrowsers, or anything else that can run in a Docker container.")])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"https://sourceforge.net/projects/grinder/",target:"_blank",rel:"noopener noreferrer"}},[e._v("The Grinder"),n("OutboundLink")],1),e._v(": Java load testing framework.")])]),e._v(" "),n("li",[n("p",[n("a",{attrs:{href:"https://github.com/Ninja-Squad/springmockk",target:"_blank",rel:"noopener noreferrer"}},[e._v("SpringMockK"),n("OutboundLink")],1),e._v(": Support for Spring Boot\nintegration tests written in Kotlin using "),n("a",{attrs:{href:"https://mockk.io/",target:"_blank",rel:"noopener noreferrer"}},[e._v("MockK"),n("OutboundLink")],1),e._v(" instead of Mockito.")])])])])}),[],!1,null,null,null);t.default=s.exports}}]);