如何在集成测试中启用UserserviceApplication的编码斜杠URL配置?
如何在集成测试中启用编码斜杠(%2F)支持
问题原因
你当前在UserserviceApplication的main方法中设置了Tomcat允许编码斜杠的系统属性,但集成测试启动时不会执行这个main方法,导致该属性未被设置。而WebMvc的configurePathMatch配置因为主类被@SpringBootTest加载,会自动生效,所以只需要补充系统属性的设置即可。
解决方案
方案1:在测试类中直接设置系统属性
在TeamControllerIT中添加静态代码块或者@BeforeClass方法,在测试启动前设置系统属性:
@ActiveProfiles("it") @RunWith(SpringRunner.class) @TestPropertySource(locations = "classpath:application-it.properties") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class TeamControllerIT { // 静态代码块,类加载时执行 static { System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true"); } @LocalServerPort private int port; @Autowired private Environment environment; // 测试方法... }
或者使用@BeforeClass注解:
@BeforeClass public static void setupEncodedSlashProperty() { System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true"); }
方案2:全局配置系统属性(推荐)
把系统属性的设置移到Spring组件中,这样不管是生产启动还是测试启动都会自动生效,无需在测试类中重复配置:
创建一个配置类:
@Component public class EncodedSlashSupportConfig { @PostConstruct public void enableEncodedSlash() { System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true"); } }
或者实现ApplicationListener监听应用启动事件:
@Component public class EncodedSlashInitializer implements ApplicationListener<ApplicationStartingEvent> { @Override public void onApplicationEvent(ApplicationStartingEvent event) { System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true"); } }
修改后可以删除UserserviceApplication的main方法中的System.setProperty代码,让配置更统一。
验证
启动集成测试后,发起包含%2F的请求,应该能正常处理,不会返回400错误。
内容的提问来源于stack exchange,提问作者Ahmet Karakaya
相关产品推荐
相关产品推荐

