Created
July 12, 2018 03:56
-
-
Save nosix/20454a50ef779ddd88d0ff9c738a5754 to your computer and use it in GitHub Desktop.
pass JSONCompareMode to JSONAssert when testing with WebTestClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RunWith(SpringRunner::class) | |
@SpringBootTest | |
@AutoConfigureWebTestClient | |
class ExampleTests { | |
@Autowired | |
private lateinit var client: WebTestClient | |
@Test | |
fun test_of_get() { | |
client.get().uri("/api/todo") | |
.exchange() | |
.expectStatus().isOk | |
.expectBody() | |
.jsonInStrict(""" | |
{ | |
"id": 1, | |
"description": "write webflux blog" | |
} | |
""".trimIndent()) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.skyscreamer.jsonassert.JSONAssert | |
import org.skyscreamer.jsonassert.JSONCompareMode | |
import org.springframework.test.web.reactive.server.EntityExchangeResult | |
import org.springframework.test.web.reactive.server.WebTestClient | |
import java.nio.charset.StandardCharsets.UTF_8 | |
import java.util.function.Consumer | |
class JsonVerifier( | |
private val json: String, | |
private val mode: JSONCompareMode | |
) : Consumer<EntityExchangeResult<ByteArray>> { | |
override fun accept(result: EntityExchangeResult<ByteArray>) { | |
try { | |
JSONAssert.assertEquals(json, getBodyAsString(result), mode) | |
} catch (ex: Exception) { | |
throw AssertionError("JSON parsing error", ex) | |
} | |
} | |
private fun getBodyAsString(result: EntityExchangeResult<ByteArray>): String { | |
val body = result.responseBody | |
if (body == null || body.isEmpty()) { | |
return "" | |
} | |
val mediaType = result.responseHeaders.contentType | |
val charset = mediaType?.charset ?: UTF_8 | |
return String(body, charset) | |
} | |
} | |
fun WebTestClient.BodyContentSpec.jsonInStrict(json: String) = consumeWith(JsonVerifier(json, JSONCompareMode.STRICT)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment