我正在尝试学习 Kotlin,并测试它如何与 Spring Boot 配合使用。我的应用程序使用 mongo 数据库来存储数据,并且我有用于检索数据的 Jersey 资源。我正在使用它进行测试spring-boot-test
and RestTestTemplate
.
The RestTestTemplate
has an exchange
方法需要一个ParameterizedTypeReference
。该类有一个受保护的构造函数。所以我设法从 Kotlin 使用它的唯一方法是这样的:
class ListOfPeople : ParameterizedTypeReference<List<Person>>()
这是我的测试方法:
@Test
fun `get list of people`() {
// create testdata
datastore.save(Person(firstname = "test1", lastname = "lastname1"))
datastore.save(Person(firstname = "test2", lastname = "lastname2"))
datastore.save(Person(firstname = "test3", lastname = "lastname2"))
datastore.save(Person(firstname = "test4", lastname = "lastname2"))
val requestEntity = RequestEntity<Any>(HttpMethod.GET, URI.create("/person"))
// create typereference for response de-serialization
class ListOfPeople : ParameterizedTypeReference<List<Person>>() // can this be done inline in the exchange method?
val responseEntity : ResponseEntity<List<Person>> = restTemplate.exchange(requestEntity, ListOfPeople())
assertNotNull(responseEntity)
assertEquals(200, responseEntity.statusCodeValue)
assertTrue( responseEntity.body.size >= 4 )
responseEntity.body.forEach { person ->
println("Found person: [${person.firstname} ${person.lastname}] " +
", born [${person.birthdate}]")
}
}
这是执行此操作的正确(或唯一)方法,还是有更好的方法?
如果有帮助,这里是整个测试的链接:github上的测试类 https://github.com/thomasandersen77/learning-kotlin/blob/master/kotlin-springboot/src/test/kotlin/org/andtho/kotlin/web/restkotlin/RestKotlinApplicationTests.kt