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

Viewed 3329

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 ?

3 Answers

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

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

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...
    }
}

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

new MediaType(MediaType.TEXT_PLAIN, StandardCharsets.UTF_8)
Related