【问题标题】:How do I specify a mediatype of text/plain;charset=UTF-8 in a Spring Boot Test如何在 Spring Boot 测试中指定 text/plain;charset=UTF-8 的媒体类型
【发布时间】:2020-09-20 16:37:36
【问题描述】:

这是我的测试:

 @Test
 fun `test config properties`() {
    mockMvc.request(HttpMethod.GET,"someUrl") {
        accept = MediaType.TEXT_PLAIN
    }.andExpect {
        status { isOk }
        content { contentType(MediaType.TEXT_PLAIN) }
    }
}

它失败了:

预期 :text/plain 实际 :text/plain;charset=UTF-8

这是将 Kotlin DSL 用于 MockMVC。

如何更改接受以允许 charset=UTF-8 ?

【问题讨论】:

  • 有一种工厂方法可以接受自定义值。试试 MediaType.valueOf("text/plain;charset=UTF-8")
  • 很好用 - 谢谢。如果您将该评论更改为答案,我会将其标记为已接受的答案。
  • 我已经添加了一个答案。谢谢。

标签: spring spring-boot spring-mvc kotlin mockmvc


【解决方案1】:

有一种工厂方法可以接受自定义值。试试:

MediaType.valueOf("text/plain;charset=UTF-8")

【讨论】:

    【解决方案2】:

    如果 charset 不是测试的目标,则 Spring Boot 使用 contentTypeCompatibleWith() 提供更灵活的 content-type 断言:

    例如,在 Kotlin DSL 中,它看起来像这样:

    mockMvc.get("/") {
        accept = TEXT_HTML
    }.andExpect {
        content {
            contentTypeCompatibleWith(TEXT_HTML)
            // ... more assertions here...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-02-15
      • 2018-05-15
      • 2023-02-06
      • 2018-01-11
      • 2021-08-05
      • 2014-09-18
      • 2020-07-30
      • 2016-12-19
      • 2022-06-10
      相关资源
      最近更新 更多