How do I specify a mediatype of text/plain;charset=UTF-8 in a Spring Boot Test
Asked Answered
O

3

6

Here's my test :

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

and it fails with this:

Expected :text/plain Actual :text/plain;charset=UTF-8

This is using the Kotlin DSL for MockMVC.

How do I change the accept to allow for charset=UTF-8 ?

Oldfashioned answered 2/6, 2020 at 8:43 Comment(0)
U
10

There is one factory method which accepts custom value. Try:

MediaType.valueOf("text/plain;charset=UTF-8")
Unhook answered 2/6, 2020 at 10:36 Comment(0)
T
4

You can also use the constructor accepting the encoding as a parameter:

new MediaType(MediaType.TEXT_PLAIN, StandardCharsets.UTF_8)
Tertian answered 23/6, 2022 at 7:28 Comment(0)
R
3

If charset is not the objective of the test Spring Boot provides more flexible assertion of the content-type using contentTypeCompatibleWith():

For instance, in Kotlin DSL it would look like this:

mockMvc.get("/") {
    accept = TEXT_HTML
}.andExpect {
    content {
        contentTypeCompatibleWith(TEXT_HTML)
        // ... more assertions here...
    }
}
Roxy answered 28/3, 2021 at 16:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.