Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use TestContext

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to use TestContext". In daily operation, I believe many people have doubts about how to use TestContext. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use TestContext". Next, please follow the editor to study!

The Spring TestContext framework (located in the org.springframework.test.context package) provides generic, annotation-driven unit and integration testing support, regardless of the test framework used. The TestContext framework also attaches great importance to convention over configuration, and you can override reasonable default values through annotation-based configuration.

In addition to the general test infrastructure, the TestContext framework provides explicit support for JUnit 4 Magi JUnit Jupiter (AKA JUnit 5) and TestNG. Abstract support classes are provided for JUnit 4 and TestNG,Spring. In addition, Spring provides custom JUnit Runner and custom JUnit rules for JUnit 4, as well as custom extensions to JUnit Jupiter that allow you to write so-called POJO test classes. POJO test classes are not required to extend specific class hierarchies, such as abstract support classes. The next section outlines the internals of the TestContext framework. If you are only interested in using the framework, but not interested in extending with your own custom listeners or custom loaders, go directly to the configuration (context management, dependency injection, transaction management, supporting classes, and annotation support sections.

3.5.1 key abstraction

The core of the framework consists of TestContextManager classes and TestContext,TestExecutionListener and SmartContextLoader interfaces. Create a TestContextManager for each test class (for example, to execute all test methods in a single test class in JUnit Jupiter). TestContextManager, in turn, manages the TestContext that contains the current test context. As the test progresses, TestContextManager also updates the status of the TestContext and delegates it to the TestExecutionListener implementation, which detects actual test execution by providing dependency injection, managing transactions, and so on. SmartContextLoader is responsible for loading ApplicationContext for a given test class. For more information and examples of various implementations, see javadoc and Spring test suites.

TestContext

TestContext encapsulates the context in which tests are executed (independent of the actual test framework in use) and provides context management and caching support for the test cases it is responsible for. If necessary, TestContext also delegates to SmartContextLoader to load the ApplicationContext.

TestContextManager

TestContextManager is the main entry point to the Spring TestContext framework and is responsible for managing a single TestContext and signaling events to each registered TestExecutionListener at a well-defined test execution point:

Before any before class or before all methods of a particular test framework.

Test case post-processing.

Before any before or the method of each specific test framework.

Before the test method is executed, but after the test settings.

After the test method is executed, but before the test disassembly.

Any method after that or each specific testing framework after that.

After any class or all methods of a particular test framework.

TestExecutionListener

TestExecutionListener defines the API that is used to react to test execution events published by the TestContextManager that registers the listener. See TestExecutionListener configuration.

Context loader

ContextLoader is a policy interface for loading ApplicationContext for integration tests managed by the Spring TestContext framework. You should implement SmartContextLoader instead of this interface to provide support for component classes, activated bean definition profiles, test property sources, context hierarchies, and WebApplicationContext support.

SmartContextLoader is an extension of the ContextLoader interface that replaces the original minimum ContextLoader SPI. Specifically, SmartContextLoader can choose to deal with resource locations, component classes, or context initializers. In addition, SmartContextLoader can set the activation Bean definition configuration file and test the property source in the context in which it loads.

Spring provides the following implementations:

DelegatingSmartContextLoader: it is one of two default loaders that is internally delegated to AnnotationConfigContextLoader, GenericXmlContextLoader, or GenericGroovyXmlContextLoader, depending on the configuration declared for the test class or the default location or the existence of the default configuration class. Groovy support is enabled only if Groovy is on the classpath.

WebDelegatingSmartContextLoader: it is one of two default loaders that is internally delegated to AnnotationConfigWebContextLoader, GenericXmlWebContextLoader, or GenericGroovyXmlWebContextLoader, depending on the configuration declared for the test class or the default location or the existence of the default configuration class. Use Web ContextLoader only if @ WebAppConfiguration exists on the test class. Groovy support is enabled only if Groovy is on the classpath.

AnnotationConfigContextLoader: loads the standard ApplicationContext from the component class.

AnnotationConfigWebContextLoader: loads WebApplicationContext from the component class.

GenericGroovyXmlContextLoader: loads the standard ApplicationContext from the resource location of the Groovy script or XML configuration file.

GenericGroovyXmlWebContextLoader: loads WebApplicationContext from the resource location of the Groovy script or XML configuration file.

GenericXmlContextLoader: loads the standard ApplicationContext from the XML resource location.

GenericXmlWebContextLoader: loads WebApplicationContext from the XML resource location.

GenericPropertiesContextLoader: loads the standard ApplicationContext from the Java properties file.

3.5.2 Boot TestContext Framework

The default configuration within the Spring TestContext framework is sufficient for all common use cases. However, sometimes the development team or third-party framework wants to change the default ContextLoader, implement custom TestContext or ContextCache, extend the default ContextCustomizerFactory and TestExecutionListener implementations, and so on. To provide low-level control over how the TestContext framework operates, Spring provides a boot strategy.

TestContextBootstrapper defines the SPI used to boot the TestContext framework. TestContextManager uses TestContextBootstrapper to load the TestExecutionListener implementation of the current test and build the TestContext it manages. You can use @ BootstrapWith directly or as meta annotations to configure custom boot policies for test classes (or test class hierarchies). If you do not explicitly configure the bootstrap by using @ bootstrap WebAppConfiguration, use DefaultTestContextBootstrapper or WebTestContextBootstrapper depending on the existence of @ bootstrap.

Since TestContextBootstrapper SPI may change in the future (to accommodate the new requirements), we strongly recommend that implementers do not implement this interface directly, but should extend AbstractTestContextBootstrapper or one of its specific subclasses.

3.5.3 TestExecutionListener configuration

Spring provides the following TestExecutionListener implementations, which are registered by default in the following order:

ServletTestExecutionListener: configure Servlet API emulation for WebApplicationContext.

DirtiesContextBeforeModesTestExecutionListener: handles @ DirtiesContext annotations for before schemas.

DependencyInjectionTestExecutionListener: provides dependency injection for the test instance.

DirtiesContextTestExecutionListener: handles @ DirtiesContext annotations for after schemas.

TransactionalTestExecutionListener: provides transaction test execution with default rollback semantics.

SqlScriptsTestExecutionListener: run the SQL script configured with the @ Sql annotation.

EventPublishingTestExecutionListener: publish test execution events to the test's ApplicationContext (see Test execution events).

Register the TestExecutionListener implementation

You can use the @ TestExecutionListeners annotation to annotate the TestExecutionListener implementation for the test class and its subclasses. For more information and examples, see annotated support and @ TestExecutionListeners's javadoc.

Default TestExecutionListener implements automatic discovery

Implement custom listeners for use in limited test scenarios by registering TestExecutionListener with @ TestExecutionListeners. However, it can be cumbersome if you need to use custom listeners throughout the test suite. This problem can be solved by supporting the automatic discovery of the default TestExecutionListener implementation through the SpringFactoriesLoader mechanism.

Specifically, the spring-test module declares all core default TestExecutionListener implementations under org.springframework.test.context.TestExecutionListener in the key in its META-INF/spring.factories properties file. Third-party frameworks and developers can contribute their TestExecutionListener implementations to the default listener list in the same way through their own META-INF/spring.factories properties files.

TestExecutionListener sequential implementation

When the TestContext framework discovers the default TestExecutionListener implementation through the above SpringFactoriesLoader mechanism, the instantiated listener will use Spring's AnnotationAwareOrderComparator for sorting, and this class will use Spring's Ordered interface and @ Order annotation for sorting. The AbstractTestExecutionListener provided by Spring and all default TestExecutionListener implementations implement Ordered with appropriate values. Therefore, third-party frameworks and developers should ensure that their default TestExecutionListener implementations are registered in the default order by implementing Ordered or declaring @ Order. See javadoc for the getOrder () method of the core default TestExecutionListener implementation for more information about which values are assigned to each core listener.

TestExecutionListener merge implementation

If a custom TestExecutionListener is registered through @ TestExecutionListeners, the default listener is not registered. In most common test scenarios, this effectively forces developers to manually declare all default listeners except any custom listeners.

The following listing demonstrates this configuration style:

ContextConfiguration@TestExecutionListeners ({MyCustomTestExecutionListener.class, ServletTestExecutionListener.class, DirtiesContextBeforeModesTestExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class, SqlScriptsTestExecutionListener.class}) class MyTest {/ / class body...}

The challenge with this approach is that it requires developers to know exactly which listeners are registered by default. In addition, the default set of listeners can vary from version to release-for example, SqlScriptsTestExecutionListener was introduced in Spring Framework 4.1 and DirtiesContextBeforeModesTestExecutionListener in Spring Framework 4.2. In addition, third-party frameworks such as Spring Boot and Spring Security register their default TestExecutionListener implementations by using the autodiscovery mechanism described above.

To avoid having to understand and redeclare all default listeners, set the mergeMode property of @ TestExecutionListeners to MergeMode.MERGE_WITH_DEFAULTS. MERGE_WITH_DEFAULTS indicates that locally declared listeners should be merged with default listeners. The merge algorithm ensures that duplicates are removed from the list and that the merged listener set is sorted according to the semantics of AnnotationAwareOrderComparator, as described in the Ordering TestExecutionListener implementation. If the listener implements Ordered or uses @ Order for annotations, it can affect where it is merged with the default value. Otherwise, when merging, locally declared listeners are appended to the default listener list.

For example, if the MyCustomTestExecutionListener class in the previous example configures the order values (for example, 500) to be less than the order of ServletTestExecutionListener (exactly 1000), MyCustomTestExecutionListener can be automatically merged with the default list. In front of ServletTestExecutionListener, and the previous example can be replaced with the following example:

@ ContextConfiguration@TestExecutionListeners (listeners = MyCustomTestExecutionListener.class, mergeMode = MERGE_WITH_DEFAULTS) class MyTest {/ / class body...}

3.5.4 Test execution event

EventPublishingTestExecutionListener, introduced in Spring Framework 5.2, provides an alternative to implementing custom TestExecutionListener. Components in the tested ApplicationContext can listen for the following events published by EventPublishingTestExecutionListener, each of which corresponds to a method in TestExecutionListener API.

BeforeTestClassEvent

PrepareTestInstanceEvent

BeforeTestMethodEvent

BeforeTestExecutionEvent

AfterTestExecutionEvent

AfterTestMethodEvent

AfterTestClassEvent

These events are published only when the ApplicationContext is already loaded.

These events can be used for a variety of reasons, such as resetting simulated bean or tracking test execution. One advantage of using test execution events instead of implementing a custom TestExecutionListener is that test execution events can be used by any Spring bean registered in the test ApplicationContext, and such bean can directly benefit from dependency injection and other features of ApplicationContext. In contrast, TestExecutionListener is not a bean in ApplicationContext.

To listen for test execution events, Spring Bean can choose to implement the org.springframework.context.ApplicationListener interface. Alternatively, you can use the @ EventListener annotation listener method and configure the listening method to listen to one of the specific event types listed above (see annotation-based event listeners). Due to the popularity of this approach, Spring provides the following dedicated @ EventListener annotations to simplify the registration of test execution event listeners. These annotations reside in the org.springframework.test.context.event.annotation package.

@ BeforeTestClass

@ PrepareTestInstance

@ BeforeTestMethod

@ BeforeTestExecution

@ AfterTestExecution

@ AfterTestMethod

@ AfterTestClass

Exception handling

By default, if the test execution event listener throws an exception when using an event, the exception is propagated to the underlying test framework in use (such as JUnit or TestNG). For example, if using BeforeTestMethodEvent causes an exception, the corresponding test method will fail because of the exception. Conversely, if the asynchronous test execution event listener throws an exception, the exception is not propagated to the underlying test framework. For more details on asynchronous exception handling, refer to the @ EventListener class-level javadoc.

Asynchronous listener

If you want specific test execution event listeners to handle events asynchronously, you can use Spring's regular @ Async support. For more details, refer to @ EventListener's class-level javadoc.

At this point, the study on "how to use TestContext" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report