Skip to content

Instantly share code, notes, and snippets.

@danieloskarsson
Created June 6, 2020 14:43
Show Gist options
  • Save danieloskarsson/2e4d22017d158fe548677f2bea088534 to your computer and use it in GitHub Desktop.
Save danieloskarsson/2e4d22017d158fe548677f2bea088534 to your computer and use it in GitHub Desktop.
// ...
@Test @Transactional @Rollback fun getZeroBookings() = get("/${organization1.slug}/${resource1.slug}/2020/04/1/1", status().isOk, jsonPath("$", hasSize<Resource>(0)))
@Test @Transactional @Rollback fun getThreeBookings() = get("/${organization1.slug}/${resource1.slug}/2020/04/1/7", status().isOk, jsonPath("$", hasSize<Resource>(3)))
@Test @Transactional @Rollback fun getBookingsWithBadDate() = get("/${organization1.slug}/${resource1.slug}/2020/04/31/7", status().isBadRequest)
// Wrapper around MockMvc
private fun post(url: String, model: Any?, vararg matchers: ResultMatcher) = test(POST, url, model, *matchers)
private fun patch(url: String, model: Any?, vararg matchers: ResultMatcher) = test(PATCH, url, model, *matchers)
private fun get(url: String, vararg matchers: ResultMatcher) = test(GET, url, null, *matchers)
private fun delete(url: String, vararg matchers: ResultMatcher) = test(DELETE, url, null, *matchers)
private fun test(httpMethod: HttpMethod, url: String, model: Any?, vararg matchers: ResultMatcher) {
val builder = when (httpMethod) {
POST -> MockMvcRequestBuilders.post(url)
PATCH -> MockMvcRequestBuilders.patch(url)
DELETE -> MockMvcRequestBuilders.delete(url)
else -> MockMvcRequestBuilders.get(url)
}.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
if (model != null) builder.content(try {
ObjectMapper().findAndRegisterModules().writeValueAsString(model)
} catch (e: Exception) {
throw RuntimeException(e)
})
val actions = mvc.perform(builder)
matchers.forEach { actions.andExpect(it) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment