Certainly! Here is an example of unit tests for the API using Kotest:
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.kotest.spring.SpringAutowireConstructorExtension
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
@SpringBootTest
@AutoConfigureMockMvc
@SpringAutowireConstructorExtension
class AccountControllerTest(@Autowired val mockMvc: MockMvc) : StringSpec() {
init {
"should create an account" {
val accountJson = """{"name":"Test"}"""
mockMvc.perform(post("/accounts")
.contentType(MediaType.APPLICATION_JSON)
.content(accountJson))
.andExpect(status().isCreated)
}
"should return the created account" {
val accountJson = """{"name":"Test"}"""
val result = mockMvc.perform(post("/accounts")
.contentType(MediaType.APPLICATION_JSON)
.content(accountJson))
.andReturn()
val responseJson = result.response.contentAsString
val id = responseJson.substringAfter(":").substringBefore(",").toLong()
val expectedJson = """{"id":$id,"name":"Test"}"""
mockMvc.perform(get("/accounts/$id"))
.andExpect(status().isOk)
.andExpect(result.response.contentAsString shouldBe expectedJson)
}
"should update an account" {
val accountJson = """{"name":"Test"}"""
val createResult = mockMvc.perform(post("/accounts")
.contentType(MediaType.APPLICATION_JSON)
.content(accountJson))
.andReturn()
val id = createResult.response.contentAsString.substringAfter(":").substringBefore(",").toLong()
val updateJson = """{"name":"Updated"}"""
mockMvc.perform(put("/accounts/$id")
.contentType(MediaType.APPLICATION_JSON)
.content(updateJson))
.andExpect(status().isOk)
val expectedJson = """{"id":$id,"name":"Updated"}"""
mockMvc.perform(get("/accounts/$id"))
.andExpect(status().isOk)
.andExpect(result.response.contentAsString shouldBe expectedJson)
}
"should delete an account" {