【问题标题】:Test static content with MockMVC in Spring Boot with Slice在 Spring Boot with Slice 中使用 MockMVC 测试静态内容
【发布时间】:2019-07-21 15:10:04
【问题描述】:

我正在尝试找出一种方法来使用 MockMVC 测试使用仅自动配置 org.springframework.web.servlet.resource.ResourceHttpRequestHandler(而不是控制器)的 WebSlice 提供内容

我尝试过这样的事情:

@RunWith(SpringRunner.class)
@WebMvcTest(
    controllers = {}
)
public class StaticAssetsMVCTest {

但 {} 是默认值,它会查找所有控制器。有没有办法排除所有控制器,但保留我的应用程序拥有的其他基本 spring-web 东西,以便我可以只测试静态资产切片?

【问题讨论】:

    标签: spring-boot spring-mvc testing spring-web mockmvc


    【解决方案1】:

    如何针对成熟的服务器测试静态内容?

    这是一个sample application 来说明我在说什么。

    此类测试的入口点是 @LeanWebTest 注释:

    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {
        MvcConfig.class,
        WebSecurityConfig.class
    })
    @EnableAutoConfiguration(exclude = {
        DataSourceAutoConfiguration.class,
        JpaRepositoriesAutoConfiguration.class
    })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface LeanWebTest {
    }
    

    @LeanWebTest 是一个@SpringBootTest,在随机端口使用完全配置的服务器。

    它指定了以下@Configuration 类:

    Spring Security overrides Cache-Control 标头。可能这不是我们想要的,尤其是静态资源。

    另请参阅:How to enable HTTP response caching in Spring Boot

    @LeanWebTest 不使用应用程序中的任何@Beans,但指定的配置类除外。 (未创建 @Controllers

    我看到以下方面适用于@LeanWebTests:

    • robots.txt文件
    • javax.servlet.Filters
    • 静态资源压缩
    • 静态资源缓存
    • 等等..

    示例应用程序有一些测试:


    请注意,该项目是概念的粗略演示

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-01
      • 2018-02-10
      • 1970-01-01
      • 2016-11-05
      • 2017-01-23
      • 2017-03-25
      • 2018-02-14
      • 2018-06-26
      相关资源
      最近更新 更多