-
Notifications
You must be signed in to change notification settings - Fork 39
io microsphere spring test util SpringTestWebUtils
Type: Class | Module: microsphere-spring-test | Package: io.microsphere.spring.test.util | Since: 1.0.0
Source:
microsphere-spring-test/src/main/java/io/microsphere/spring/test/util/SpringTestWebUtils.java
Web Utilities class for Spring Test
public abstract class SpringTestWebUtilsAuthor: Mercy
-
Introduced in:
1.0.0 -
Current Project Version:
0.2.27-SNAPSHOT
This component is tested and compatible with the following Java versions:
| Java Version | Status |
|---|---|
| Java 17 | ✅ Compatible |
| Java 21 | ✅ Compatible |
| Java 25 | ✅ Compatible |
NativeWebRequest request = SpringTestWebUtils.createWebRequest();NativeWebRequest request = SpringTestWebUtils.createWebRequest(req -> {
req.setMethod("POST");
req.setRequestURI("/api/users");
req.addHeader("Content-Type", "application/json");
req.setParameter("id", "123");
});NativeWebRequest request = SpringTestWebUtils.createWebRequest("/api/users/123");NativeWebRequest request = SpringTestWebUtils.createWebRequestWithParams(
"name", "John Doe",
"age", "30"
);NativeWebRequest request = SpringTestWebUtils.createWebRequestWithHeaders(
"Content-Type", "application/json",
"Authorization", "Bearer token123"
);Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer token123");
NativeWebRequest request = SpringTestWebUtils.createWebRequestWithHeaders(headers);NativeWebRequest preFlightRequest = SpringTestWebUtils.createPreFightRequest();NativeWebRequest request = SpringTestWebUtils.createWebRequest();
request.setAttribute("key1", "value1", RequestAttributes.SCOPE_REQUEST);
request.setAttribute("key2", "value2", RequestAttributes.SCOPE_REQUEST);
// Clear all request-scoped attributes
SpringTestWebUtils.clearAttributes(request);NativeWebRequest request = SpringTestWebUtils.createWebRequest();
request.setAttribute("key1", "value1", RequestAttributes.SCOPE_REQUEST);
request.setAttribute("key2", "value2", RequestAttributes.SCOPE_SESSION);
// Clear all request-scoped attributes
SpringTestWebUtils.clearAttributes(request, RequestAttributes.SCOPE_REQUEST);
// Clear all session-scoped attributes
SpringTestWebUtils.clearAttributes(request, RequestAttributes.SCOPE_SESSION);Add the following dependency to your pom.xml:
<dependency>
<groupId>io.github.microsphere-projects</groupId>
<artifactId>microsphere-spring-test</artifactId>
<version>${microsphere-spring.version}</version>
</dependency>Tip: Use the BOM (
microsphere-spring-dependencies) for consistent version management. See the Getting Started guide.
import io.microsphere.spring.test.util.SpringTestWebUtils;| Method | Description |
|---|---|
createWebRequest |
Creates a new instance of NativeWebRequest with default settings. |
createWebRequest |
Creates a new instance of NativeWebRequest with custom settings provided by the given Consumer. |
createWebRequest |
Creates a new instance of NativeWebRequest with the specified request URI. |
createWebRequestWithParams |
Creates a new instance of NativeWebRequest with the specified request parameters. |
createWebRequestWithHeaders |
Creates a new instance of NativeWebRequest with the specified request headers. |
createWebRequestWithHeaders |
Creates a new instance of NativeWebRequest with the specified request headers. |
createPreFightRequest |
Creates a new instance of NativeWebRequest for CORS pre-flight requests. |
clearAttributes |
Clears all attributes from the request scope of the given NativeWebRequest. |
clearAttributes |
Clears all attributes from the specified scope of the given NativeWebRequest. |
public static NativeWebRequest createWebRequest()Creates a new instance of NativeWebRequest with default settings.
This method is equivalent to calling #createWebRequest(Consumer) with an empty consumer.
`NativeWebRequest request = SpringTestWebUtils.createWebRequest(); `
public static NativeWebRequest createWebRequest(Consumer<MockHttpServletRequest> requestBuilder)Creates a new instance of NativeWebRequest with custom settings provided by the given Consumer.
This method allows for flexible configuration of the underlying MockHttpServletRequest
before creating the ServletWebRequest. The consumer can modify any aspect of the request,
such as headers, parameters, method, URI, etc.
`NativeWebRequest request = SpringTestWebUtils.createWebRequest(req -> {
req.setMethod("POST");
req.setRequestURI("/api/users");
req.addHeader("Content-Type", "application/json");
req.setParameter("id", "123");
`);
}
public static NativeWebRequest createWebRequest(String requestURI)Creates a new instance of NativeWebRequest with the specified request URI.
This method configures the underlying MockHttpServletRequest with the given URI
and sets the #PATH_ATTRIBUTE to the same value. It's a convenient way to create
a web request for a specific endpoint.
`NativeWebRequest request = SpringTestWebUtils.createWebRequest("/api/users/123");
`
public static NativeWebRequest createWebRequestWithParams(Object... params)Creates a new instance of NativeWebRequest with the specified request parameters.
This method configures the underlying MockHttpServletRequest with the given parameters
using io.microsphere.collection.MapUtils#of(Object...). The parameters are passed as
key-value pairs in the form of key1, value1, key2, value2, ....
`NativeWebRequest request = SpringTestWebUtils.createWebRequestWithParams(
"name", "John Doe",
"age", "30"
);
`
public static NativeWebRequest createWebRequestWithHeaders(Object... headers)Creates a new instance of NativeWebRequest with the specified request headers.
This method configures the underlying MockHttpServletRequest with the given headers
using io.microsphere.collection.MapUtils#of(Object...). The headers are passed as
key-value pairs in the form of key1, value1, key2, value2, ....
`NativeWebRequest request = SpringTestWebUtils.createWebRequestWithHeaders(
"Content-Type", "application/json",
"Authorization", "Bearer token123"
);
`
public static NativeWebRequest createWebRequestWithHeaders(Map<String, String> headers)Creates a new instance of NativeWebRequest with the specified request headers.
This method configures the underlying MockHttpServletRequest with the given headers
using a Map. The headers are passed as a map of key-value pairs.
`Map headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer token123");
NativeWebRequest request = SpringTestWebUtils.createWebRequestWithHeaders(headers);
`
public static NativeWebRequest createPreFightRequest()Creates a new instance of NativeWebRequest for CORS pre-flight requests.
This method configures the underlying MockHttpServletRequest with the OPTIONS method
and adds the following headers:
- :METHOD: - set to "OPTIONS"
- Origin - set to "*"
- Access-Control-Request-Method - set to "*"
`NativeWebRequest preFlightRequest = SpringTestWebUtils.createPreFightRequest(); `
public static void clearAttributes(@Nonnull NativeWebRequest request)Clears all attributes from the request scope of the given NativeWebRequest.
This method removes all attributes currently set in the request scope. It's useful for cleaning up request state between tests or operations.
`NativeWebRequest request = SpringTestWebUtils.createWebRequest();
request.setAttribute("key1", "value1", RequestAttributes.SCOPE_REQUEST);
request.setAttribute("key2", "value2", RequestAttributes.SCOPE_REQUEST);
// Clear all request-scoped attributes
SpringTestWebUtils.clearAttributes(request);
`
public static void clearAttributes(@Nonnull NativeWebRequest request, int scope)Clears all attributes from the specified scope of the given NativeWebRequest.
This method removes all attributes currently set in the specified scope (either request or session). It's useful for cleaning up request or session state between tests or operations.
`NativeWebRequest request = SpringTestWebUtils.createWebRequest();
request.setAttribute("key1", "value1", RequestAttributes.SCOPE_REQUEST);
request.setAttribute("key2", "value2", RequestAttributes.SCOPE_SESSION);
// Clear all request-scoped attributes
SpringTestWebUtils.clearAttributes(request, RequestAttributes.SCOPE_REQUEST);
// Clear all session-scoped attributes
SpringTestWebUtils.clearAttributes(request, RequestAttributes.SCOPE_SESSION);
`
NativeWebRequestMockHttpServletRequest
This documentation was auto-generated from the source code of microsphere-spring.
spring-context
- AbstractInjectionPointDependencyResolver
- AbstractSmartLifecycle
- AbstractSpringResourceURLConnection
- AnnotatedBeanCapableImportBeanDefinitionRegistrar
- AnnotatedBeanCapableImportCandidate
- AnnotatedBeanCapableImportSelector
- AnnotatedBeanDefinitionRegistryUtils
- AnnotatedInjectionBeanPostProcessor
- AnnotatedInjectionPointDependencyResolver
- AnnotatedPropertySourceLoader
- AnnotationBeanDefinitionRegistryPostProcessor
- AnnotationUtils
- ApplicationContextUtils
- ApplicationEventInterceptor
- ApplicationEventInterceptorChain
- ApplicationListenerInterceptor
- ApplicationListenerInterceptorChain
- AutoRegistrationBean
- AutoRegistrationBeanRegistrar
- AutowireCandidateResolvingListener
- AutowiredInjectionPointDependencyResolver
- BeanCapableImportCandidate
- BeanDefinitionUtils
- BeanDependencyResolver
- BeanFactoryListener
- BeanFactoryListenerAdapter
- BeanFactoryListeners
- BeanFactoryUtils
- BeanListener
- BeanListenerAdapter
- BeanListeners
- BeanMethodInjectionPointDependencyResolver
- BeanPropertyChangedEvent
- BeanRegistrar
- BeanSource
- BeanTimeStatistics
- BeanUtils
- CollectingConfigurationPropertyListener
- CompositeAutowireCandidateResolvingListener
- ConfigurationBeanAliasGenerator
- ConfigurationBeanBinder
- ConfigurationBeanBindingPostProcessor
- ConfigurationBeanBindingRegistrar
- ConfigurationBeanBindingsRegister
- ConfigurationBeanCustomizer
- ConfigurationPropertyOverrideAnnotationAttributesStrategy
- ConfigurationPropertyRepository
- ConstructionInjectionPointDependencyResolver
- ConversionServiceResolver
- ConversionServiceUtils
- DefaultApplicationEventInterceptorChain
- DefaultApplicationListenerInterceptorChain
- DefaultBeanDependencyResolver
- DefaultConfigurationBeanAliasGenerator
- DefaultConfigurationBeanBinder
- DefaultPropertiesPropertySource
- DefaultPropertiesPropertySourceLoader
- DefaultPropertiesPropertySources
- DefaultPropertiesPropertySourcesLoader
- DefaultResourceComparator
- DelegatingFactoryBean
- Dependency
- DependencyAnalysisBeanFactoryListener
- DependencyTreeWalker
- EnableAutoRegistrationBean
- EnableConfigurationBeanBinding
- EnableConfigurationBeanBindings
- EnableEventExtension
- EnableSpringConverterAdapter
- EnableSpringConverterAdapterRegistrar
- EnableTTLCaching
- EnvironmentListener
- EnvironmentUtils
- EventExtensionAttributes
- EventExtensionRegistrar
- EventPublishingBeanAfterProcessor
- EventPublishingBeanBeforeProcessor
- EventPublishingBeanInitializer
- ExposingClassPathBeanDefinitionScanner
- FilterMode
- GenericAnnotationAttributes
- GenericApplicationListenerAdapter
- GenericBeanNameGenerator
- GenericBeanPostProcessorAdapter
- HyphenAliasGenerator
- ImmutableMapPropertySource
- ImportOptional
- ImportOptionalSelector
- InjectionPointDependencyResolver
- InjectionPointDependencyResolvers
- InterceptingApplicationEventMulticaster
- InterceptingApplicationEventMulticasterProxy
- InterceptingApplicationListener
- JavaBeansPropertyChangeListenerAdapter
- JoinAliasGenerator
- JsonPropertySource
- JsonPropertySourceFactory
- ListenableAutowireCandidateResolver
- ListenableAutowireCandidateResolverInitializer
- ListenableConfigurableEnvironment
- ListenableConfigurableEnvironmentInitializer
- LoggingAutowireCandidateResolvingListener
- LoggingBeanFactoryListener
- LoggingBeanListener
- LoggingEnvironmentListener
- LoggingSmartLifecycle
- MethodParameterUtils
- MimeTypeUtils
- NamedBeanHolderComparator
- OnceApplicationContextEventListener
- OverrideAnnotationAttributes
- OverrideAnnotationAttributesStrategy
- ParallelPreInstantiationSingletonsBeanFactoryListener
- ProfileListener
- PropertiesUtils
- PropertyConstants
- PropertyResolverListener
- PropertyResolverUtils
- PropertySourceChangedEvent
- PropertySourceExtension
- PropertySourceExtensionAttributes
- PropertySourceExtensionLoader
- PropertySourcesChangedEvent
- PropertySourcesUtils
- PropertyValuesUtils
- ResolvableDependencyTypeFilter
- ResolvablePlaceholderAnnotationAttributes
- ResourceInjectionPointDependencyResolver
- ResourceLoaderUtils
- ResourcePropertySource
- ResourcePropertySourceLoader
- ResourcePropertySources
- ResourcePropertySourcesLoader
- ResourceUtils
- ResourceYamlProcessor
- SpringConverterAdapter
- SpringDelegatingBeanProtocolURLConnectionFactory
- SpringEnvironmentURLConnectionFactory
- SpringFactoriesLoaderUtils
- SpringProfilesURLConnectionAdapter
- SpringPropertySourcesURLConnectionAdapter
- SpringProtocolURLStreamHandler
- SpringResourceURLConnection
- SpringResourceURLConnectionAdapter
- SpringResourceURLConnectionFactory
- SpringSubProtocolURLConnectionFactory
- SpringVersion
- SpringVersionUtils
- TTLCachePut
- TTLCacheResolver
- TTLCacheable
- TTLCachingConfiguration
- TTLContext
- UnderScoreJoinAliasGenerator
- YamlPropertySource
- YamlPropertySourceFactory
spring-guice
spring-jdbc
- CompoundJdbcEventListenerFactory
- EnableP6DataSource
- NoOpP6LoadableOptions
- P6DataSourceBeanDefinitionRegistrar
- P6DataSourceBeanPostProcessor
- PropertySourcesP6LoadableOptionsAdapter
- SpringP6SpyURLConnectionFactory
spring-test
- AbstractWebFluxTest
- AbstractWebMvcTest
- AnnotatedTypeMetadataTestFactory
- EmbeddedDataBaseBeanDefinitionRegistrar
- EmbeddedDataBaseBeanDefinitionsRegistrar
- EmbeddedDatabaseType
- EmbeddedTomcatConfiguration
- EmbeddedTomcatContextLoader
- EmbeddedTomcatMergedContextConfiguration
- EmbeddedTomcatTestContextBootstrapper
- EmbeddedZookeeperServer
- EmbeddedZookeeperServerTestExecutionListener
- EnableEmbeddedDatabase
- EnableEmbeddedDatabases
- MockServletWebRequest
- PersonHandler
- PersonHandler
- RouterFunctionTestConfig
- RouterFunctionTestConfig
- ServletTestUtils
- SimpleUrlHandlerMappingTestConfig
- SimpleUrlHandlerMappingTestConfig
- SpringLoggingTest
- SpringTestUtils
- SpringTestWebUtils
- TestConditionContext
- TestController
- TestFilter
- TestFilterRegistration
- TestServlet
- TestServletContext
- TestServletContextListener
- TestServletRegistration
- User
- WebTestUtils
spring-web
- AbstractNameValueExpression
- AbstractWebEndpointMappingFactory
- AbstractWebRequestRule
- CompositeWebEndpointMappingRegistry
- CompositeWebRequestRule
- ConsumeMediaTypeExpression
- DelegatingHandlerMethodAdvice
- EnableWebExtension
- FilterRegistrationWebEndpointMappingFactory
- FilteringWebEndpointMappingRegistry
- GenericMediaTypeExpression
- HandlerMetadata
- HandlerMethodAdvice
- HandlerMethodArgumentInterceptor
- HandlerMethodArgumentsResolvedEvent
- HandlerMethodInterceptor
- HandlerMethodMetadata
- HttpUtils
- Jackson2WebEndpointMappingFactory
- MediaTypeExpression
- MediaTypeUtils
- NameValueExpression
- ProduceMediaTypeExpression
- PropertyConstants
- RegistrationWebEndpointMappingFactory
- RequestAttributesUtils
- RequestContextStrategy
- ServletRegistrationWebEndpointMappingFactory
- ServletWebEndpointMappingResolver
- SimpleWebEndpointMappingRegistry
- SmartWebEndpointMappingFactory
- SpringWebHelper
- SpringWebType
- UnknownSpringWebHelper
- WebEndpointMapping
- WebEndpointMappingFactory
- WebEndpointMappingFilter
- WebEndpointMappingRegistrar
- WebEndpointMappingRegistry
- WebEndpointMappingResolver
- WebEndpointMappingsReadyEvent
- WebEventPublisher
- WebExtensionBeanDefinitionRegistrar
- WebRequestConsumesRule
- WebRequestHeaderExpression
- WebRequestHeadersRule
- WebRequestMethodsRule
- WebRequestParamExpression
- WebRequestParamsRule
- WebRequestPattensRule
- WebRequestProducesRule
- WebRequestRule
- WebRequestUtils
- WebScope
- WebSource
- WebTarget
- WebType
- WebUtils
spring-webflux
- CompositeWebFilter
- ConsumingWebEndpointMappingAdapter
- DelegatingWebFilter
- EnableWebFluxExtension
- HandlerMappingWebEndpointMappingFactory
- HandlerMappingWebEndpointMappingResolver
- HandlerMetadataWebEndpointMappingFactory
- InterceptingHandlerMethodProcessor
- MonoUtils
- RequestContextWebFilter
- RequestHandledEventPublishingWebFilter
- RequestMappingMetadataWebEndpointMappingFactory
- RequestPredicateKind
- RequestPredicateVisitorAdapter
- ReversedProxyHandlerMapping
- RouterFunctionVisitorAdapter
- ServerRequestHandledEvent
- ServerWebRequest
- SpringWebFluxHelper
- StoringRequestBodyArgumentInterceptor
- StoringResponseBodyReturnValueInterceptor
- WebFluxExtensionBeanDefinitionRegistrar
- WebServerScope
- WebServerUtils
spring-webmvc
- AbstractPageRenderContextHandlerInterceptor
- AnnotatedMethodHandlerInterceptor
- ConfigurableContentNegotiationManagerWebMvcConfigurer
- ConsumingWebEndpointMappingAdapter
- ContentCachingFilter
- EnableWebMvcExtension
- EnableWebMvcExtensionListener
- ExclusiveViewResolverApplicationListener
- HandlerMappingWebEndpointMappingFactory
- HandlerMappingWebEndpointMappingResolver
- HandlerMetadataWebEndpointMappingFactory
- HandlerMethodArgumentResolverAdvice
- InterceptingHandlerMethodProcessor
- LazyCompositeHandlerInterceptor
- LoggingHandlerMethodArgumentResolverAdvice
- LoggingMethodHandlerInterceptor
- LoggingPageRenderContextHandlerInterceptor
- MethodHandlerInterceptor
- PropertyConstants
- RequestBodyAdviceAdapter
- RequestMappingMetadata
- RequestMappingMetadataWebEndpointMappingFactory
- RequestPredicateVisitorAdapter
- ResponseBodyAdviceAdapter
- ReversedProxyHandlerMapping
- RouterFunctionVisitorAdapter
- SpringWebMvcHelper
- StoringRequestBodyArgumentAdvice
- StoringResponseBodyReturnValueAdvice
- ViewResolverUtils
- ViewUtils
- WebMvcExtensionBeanDefinitionRegistrar
- WebMvcExtensionConfiguration
- WebMvcUtils
- WebUtils