SpringBoot Test的webEnvironment源码解读

 更新时间:2023年09月18日 10:10:41   作者:codecraft  
这篇文章主要为大家介绍了SpringBoot Test的webEnvironment源码解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

本文主要研究一下SpringBootTest的webEnvironment

SpringBootTest

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@ExtendWith({SpringExtension.class})
public @interface SpringBootTest {
    @AliasFor("properties")
    String[] value() default {};
    @AliasFor("value")
    String[] properties() default {};
    String[] args() default {};
    Class<?>[] classes() default {};
    WebEnvironment webEnvironment() default SpringBootTest.WebEnvironment.MOCK;
}
SpringBootTest的webEnvironment默认为SpringBootTest.WebEnvironment.MOCK

WebEnvironment

/**
     * An enumeration web environment modes.
     */
    enum WebEnvironment {
        /**
         * Creates a {@link WebApplicationContext} with a mock servlet environment if
         * servlet APIs are on the classpath, a {@link ReactiveWebApplicationContext} if
         * Spring WebFlux is on the classpath or a regular {@link ApplicationContext}
         * otherwise.
         */
        MOCK(false),
        /**
         * Creates a web application context (reactive or servlet based) and sets a
         * {@code server.port=0} {@link Environment} property (which usually triggers
         * listening on a random port). Often used in conjunction with a
         * {@link LocalServerPort @LocalServerPort} injected field on the test.
         */
        RANDOM_PORT(true),
        /**
         * Creates a (reactive) web application context without defining any
         * {@code server.port=0} {@link Environment} property.
         */
        DEFINED_PORT(true),
        /**
         * Creates an {@link ApplicationContext} and sets
         * {@link SpringApplication#setWebApplicationType(WebApplicationType)} to
         * {@link WebApplicationType#NONE}.
         */
        NONE(false);
        private final boolean embedded;
        WebEnvironment(boolean embedded) {
            this.embedded = embedded;
        }
        /**
         * Return if the environment uses an {@link ServletWebServerApplicationContext}.
         * @return if an {@link ServletWebServerApplicationContext} is used.
         */
        public boolean isEmbedded() {
            return this.embedded;
        }
    }
WebEnvironment有四个枚举,分别是MOCK、RANDOM_PORT、DEFINED_PORT、NONE

SpringBootTestContextBootstrapper

spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextBootstrapper.java

public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstrapper {
    private static final String[] WEB_ENVIRONMENT_CLASSES = { "javax.servlet.Servlet",
            "org.springframework.web.context.ConfigurableWebApplicationContext" };
    private static final String REACTIVE_WEB_ENVIRONMENT_CLASS = "org.springframework."
            + "web.reactive.DispatcherHandler";
    private static final String MVC_WEB_ENVIRONMENT_CLASS = "org.springframework.web.servlet.DispatcherServlet";
    private static final String JERSEY_WEB_ENVIRONMENT_CLASS = "org.glassfish.jersey.server.ResourceConfig";
    private static final String ACTIVATE_SERVLET_LISTENER = "org.springframework.test."
            + "context.web.ServletTestExecutionListener.activateListener";
    private static final Log logger = LogFactory.getLog(SpringBootTestContextBootstrapper.class);
    @Override
    public TestContext buildTestContext() {
        TestContext context = super.buildTestContext();
        verifyConfiguration(context.getTestClass());
        WebEnvironment webEnvironment = getWebEnvironment(context.getTestClass());
        if (webEnvironment == WebEnvironment.MOCK && deduceWebApplicationType() == WebApplicationType.SERVLET) {
            context.setAttribute(ACTIVATE_SERVLET_LISTENER, true);
        }
        else if (webEnvironment != null && webEnvironment.isEmbedded()) {
            context.setAttribute(ACTIVATE_SERVLET_LISTENER, false);
        }
        return context;
    }
    //......
}
SpringBootTestContextBootstrapper继承了DefaultTestContextBootstrapper,其buildTestContext方法会判断webEnvironment,然后决定ACTIVATE_SERVLET_LISTENER是设置为true还是false,在为MOCK的时候该值为true

ServletTestExecutionListener

spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java

private boolean isActivated(TestContext testContext) {
        return Boolean.TRUE.equals(testContext.getAttribute(ACTIVATE_LISTENER)) || AnnotatedElementUtils.hasAnnotation(testContext.getTestClass(), WebAppConfiguration.class);
    }
    private void setUpRequestContextIfNecessary(TestContext testContext) {
        if (!isActivated(testContext) || alreadyPopulatedRequestContextHolder(testContext)) {
            return;
        }
        ApplicationContext context = testContext.getApplicationContext();
        if (context instanceof WebApplicationContext) {
            WebApplicationContext wac = (WebApplicationContext) context;
            ServletContext servletContext = wac.getServletContext();
            Assert.state(servletContext instanceof MockServletContext, () -> String.format(
                        "The WebApplicationContext for test context %s must be configured with a MockServletContext.",
                        testContext));
            if (logger.isDebugEnabled()) {
                logger.debug(String.format(
                        "Setting up MockHttpServletRequest, MockHttpServletResponse, ServletWebRequest, and RequestContextHolder for test context %s.",
                        testContext));
            }
            MockServletContext mockServletContext = (MockServletContext) servletContext;
            MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
            request.setAttribute(CREATED_BY_THE_TESTCONTEXT_FRAMEWORK, Boolean.TRUE);
            MockHttpServletResponse response = new MockHttpServletResponse();
            ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
            RequestContextHolder.setRequestAttributes(servletWebRequest);
            testContext.setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
            testContext.setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
            if (wac instanceof ConfigurableApplicationContext) {
                @SuppressWarnings("resource")
                ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) wac;
                ConfigurableListableBeanFactory bf = configurableApplicationContext.getBeanFactory();
                bf.registerResolvableDependency(MockHttpServletResponse.class, response);
                bf.registerResolvableDependency(ServletWebRequest.class, servletWebRequest);
            }
        }
    }
ServletTestExecutionListener的isActivated会判断ACTIVATE_SERVLET_LISTENER是不是设置为true,或者testClass有标注@WebAppConfiguration; setUpRequestContextIfNecessary方法会调用isActivated来决定是否初始化MockHttpServletRequest等设置

小结

SpringBootTest的webEnvironment默认为SpringBootTest.WebEnvironment.MOCK,它会设置ACTIVATE_SERVLET_LISTENER是设置为true,即在ServletTestExecutionListener的isActivated为true,在setUpRequestContextIfNecessary方法会初始化MockHttpServletRequest、MockHttpServletResponse等。

以上就是SpringBootTest的webEnvironment源码解读的详细内容,更多关于SpringBootTest webEnvironment的资料请关注脚本之家其它相关文章!

相关文章

  • Java 房屋租赁系统的实现流程

    Java 房屋租赁系统的实现流程

    读万卷书不如行万里路,只学书上的理论是远远不够的,只有在实战中才能获得能力的提升,本篇文章手把手带你用java+SSM+jsp+mysql+maven实现一个房屋租赁系统,大家可以在过程中查缺补漏,提升水平
    2021-11-11
  • 浅谈springboot 属性定义

    浅谈springboot 属性定义

    本篇文章主要介绍了浅谈springboot 属性定义,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • IDEA2020.1启动SpringBoot项目出现java程序包:xxx不存在

    IDEA2020.1启动SpringBoot项目出现java程序包:xxx不存在

    这篇文章主要介绍了IDEA2020.1启动SpringBoot项目出现java程序包:xxx不存在,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-06-06
  • Java实现调用MySQL存储过程详解

    Java实现调用MySQL存储过程详解

    相信大家都知道存储过程是在大型数据库系统中,一组为了完成特定功能的SQL语句集。存储过程是数据库中的一个重要对象,任何一个设计良好的数据库应用程序都应该用到存储过程。Java调用mysql存储过程,实现如下,有需要的朋友们可以参考借鉴,下面来一起看看吧。
    2016-11-11
  • Java中将MultipartFile和File互转的方法详解

    Java中将MultipartFile和File互转的方法详解

    我们在开发过程中经常需要接收前端传来的文件,通常需要处理MultipartFile格式的文件,今天来介绍一下MultipartFile和File怎么进行优雅的互转,需要的朋友可以参考下
    2023-10-10
  • Java中的HashMap集合深度解析

    Java中的HashMap集合深度解析

    这篇文章主要介绍了Java中的HashMap集合深度解析, HashMap可以说是Java中最常用的集合类框架之一,是Java语言中非常典型的数据结构,我们总会在不经意间用到它,很大程度上方便了我们日常开发,需要的朋友可以参考下
    2023-09-09
  • 基于jQuery获取table数据发送到后端

    基于jQuery获取table数据发送到后端

    这篇文章主要介绍了基于jQuery获取table数据发送到后端,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • JsonObject的属性与值的判空(Null值)处理方式

    JsonObject的属性与值的判空(Null值)处理方式

    这篇文章主要介绍了JsonObject的属性与值的判空(Null值)处理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • Java中的forEach循环详细解读

    Java中的forEach循环详细解读

    这篇文章主要介绍了Java中的forEach循环详细解读,不要再foreach循环里面进行元素的add和remove,如果你非要进行remove元素,那么请使用Iterator方式,如果存在并发,那么你一定要选择加锁,需要的朋友可以参考下
    2023-12-12
  • SpringMVC使用hibernate-validator进行参数校验最佳实践记录

    SpringMVC使用hibernate-validator进行参数校验最佳实践记录

    这篇文章主要介绍了SpringMVC使用hibernate-validator进行参数校验最佳实践,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-05-05

最新评论