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的资料请关注脚本之家其它相关文章!

相关文章

  • 一文教你学会如何使用MyBatisPlus

    一文教你学会如何使用MyBatisPlus

    本篇文章,我们通过 MyBatis Plus 来对一张表进行 CRUD 操作,来看看是如何简化我们开发的,文中通过代码示例介绍的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
    2024-05-05
  • SpringMVC路径匹配中使用通配符问题

    SpringMVC路径匹配中使用通配符问题

    这篇文章主要介绍了SpringMVC路径匹配中使用通配符问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • 打印Java程序的线程栈信息方式

    打印Java程序的线程栈信息方式

    这篇文章主要介绍了打印Java程序的线程栈信息方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • java多种幻灯片切换特效(经典)

    java多种幻灯片切换特效(经典)

    功能说明: 代码实现了多种幻灯片变换特效. 如:淡入淡出、缓慢覆盖、旋转覆盖等10多种变换效果。
    2013-03-03
  • SpringBoot解决yml明文密码问题的方法

    SpringBoot解决yml明文密码问题的方法

    在现代的软件开发中,安全性是一个重要的考量因素,对于使用SpringBoot框架开发的应用程序而言,敏感信息如数据库密码、API密钥等通常存储在YAML配置文件中,而这些文件往往是明文存储,存在安全隐患,所以本文介绍了SpringBoot解决yml明文密码问题的方法
    2024-07-07
  • JAVA接入DeepSeek满血版的详细指南(问答接入、流式接入双模式)

    JAVA接入DeepSeek满血版的详细指南(问答接入、流式接入双模式)

    硅基流动推出了功能完备的DeepSeek满血版,然而众多用户在尝试接入大型模型时仍面临诸多挑战,特别是在流式接入方面,今天,我将引领大家通过Java实现双模式接入DeepSeek满血版,需要的朋友可以参考下
    2025-03-03
  • SpringBoot如何使用Scala进行开发的实现

    SpringBoot如何使用Scala进行开发的实现

    这篇文章主要介绍了SpringBoot如何使用Scala进行开发的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • Java中的OpenTracing使用实例

    Java中的OpenTracing使用实例

    这篇文章主要介绍了Java中的OpenTracing使用实例,主要的OpenTracing API将所有主要组件声明为接口以及辅助类,例如Tracer,Span,SpanContext,Scope,ScopeManager,Format(用映射定义通用的SpanContext注入和提取格式),需要的朋友可以参考下
    2024-01-01
  • idea批量启动多个微服务具体实现

    idea批量启动多个微服务具体实现

    这篇文章主要给大家介绍了关于idea批量启动多个微服务的具体实现,在微服务开发过程中,我们经常要在本地启动很多个微服务,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2023-07-07
  • java中File类应用遍历文件夹下所有文件

    java中File类应用遍历文件夹下所有文件

    这篇文章主要为大家详细介绍了java中File类应用遍历文件夹下所有文件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-08-08

最新评论