我正在尝试学习Kotlin,并测试它如何在Spring Boot中工作。我的应用程序使用mongo数据库存储数据,并且我有一个Jersey资源来检索数据。我正在使用spring-boot-test
和RestTestTemplate
对其进行测试。RestTestTemplate
具有采用exchange
的ParameterizedTypeReference
方法。此类具有 protected 构造函数。因此,我从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}]")
}
}
这是这样做的正确(或唯一)方法,还是有更好的方法?
如果有帮助,这里是整个测试的链接:testclass on github
最佳答案
尽管使用对象表达式的答案是正确的,并且直接等效于您在Java中的实现方式,但是如果需要许多ParameterizedTypeReference
,则经过修饰的类型参数可以使您简化它:
inline fun <reified T> typeReference() = object : ParameterizedTypeReference<T>() {}
// called as
restTemplate.exchange(requestEntity, typeReference<List<Person>>())
当编译器看到
typeReference<SomeType>
调用时,它将被定义替换,因此结果与您编写object : ParameterizedTypeReference<SomeType>() {}
相同。