首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在使用@SpringBootTest运行的测试中定义tomcat属性

在使用@SpringBootTest运行的测试中定义tomcat属性
EN

Stack Overflow用户
提问于 2022-10-04 12:14:25
回答 1查看 92关注 0票数 1

我的应用程序使用spring 2.5.5。

在应用程序启动时,我将Tomcat的属性设置为allow encoded slash in @PathVariable

代码语言:javascript
运行
复制
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
        SpringApplication.run(App.class, args);
    }

}

当我启动应用程序时,一切都很好,除了集成测试之外:

代码语言:javascript
运行
复制
@ActiveProfiles("test-connected")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@ExtendWith(SpringExtension.class)
class GlobalFullTest {

调试org.apache.tomcat.util.buf.UDecoder类时:当加载类时,我看到属性org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASHnull,因此设置了默认值false

我尝试了以下几点:

application-test-connected.yaml

  • Using WebServerFactoryCustomizerH 222F 223中添加properties = { "org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true" }的测试

  • @BeforeAll方法中的
  • 添加System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");

代码语言:javascript
运行
复制
@Configuration
public class WebServerConfiguration {

    @Bean
    public WebServerFactoryCustomizer<TomcatServletWebServerFactory> customizer() {
        return factory -> factory.addConnectorCustomizers(connector -> connector.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true"));
    }

}

但是所有这些都不起作用:当属性被org.apache.tomcat.util.buf.UDecoder类检索时,它的值总是null

如何在加载org.apache.tomcat.util.buf.UDecoder类之前设置属性?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-04 13:18:22

提及How to set environment variable or system property in spring tests?

最简单的方法

遵循add static initializer in the class

代码语言:javascript
运行
复制
...
class GlobalFullTest {
    static {
        System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
    }
...
}
down side is we need to copy that for every test.

清洁道

create ApplicationContextInitializer,可以重用in the Spring application和任何其他测试。

代码语言:javascript
运行
复制
public class CustomApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>
{
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext)
    {
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
    }
}

...
@ContextConfiguration(initializers = CustomApplicationContextInitializer.class,...)
class GlobalFullTest {
...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73947706

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档