spring-boot - 如何将页面的内容作为列表获取而不是列表在 Kotlin 中使用 RestTemplate
问题描述
控制器接口
interface BrandController {
fun findDTOs(pageable: Pageable): ResponseEntity<Page<SomeDTO>>
}
简化了我的测试
var response: ResponseEntity<*>
@Test
fun `test`() {
`given TestRestTemplate`()
`when findDTOs`()
`then check body`()
}
protected fun `given not authorization`() {
restTemplate = TestRestTemplate()
}
private fun `when findDTOs`() {
// RestResponsePage<T> extends PageImpl<T>
response = restTemplate.getForEntity<RestResponsePage<SomeDTO>>(createUrlWithParams(url, requestPage))
}
private fun `then check body`() {
val body: Page<SomeDTO> = response.body as Page<SomeDTO> // body: "Page 2 of 2 containing java.util.LinkedHashMap instances"
assertEquals(requestPage.size, body.size) // success
val content: List<SomeDTO> = body.content as List<SomeDTO> // content: size = 10 body: "Page 2 of 2 containing java.util.LinkedHashMap instances"
content.forEachIndexed { index, someDTO: SomeDTO-> //Error
assertEquals(expectedList[index].name, someDTO.name)
assertEquals(expectedList[index].id, someDTO.id)
}
}
错误是:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com....SomeDTO
我怎样才能获得页面的内容List<AnyDTO>
而不是作为List<java.util.LinkedHashMap>
我这样做是为了通过TestRestTemplate return JSON String来验证内容的正确性,但是我想以这种方式进行
解决方案
我不能说这里的特定问题是什么,但我通常不会PageImpl
用来表示我的分页资源。您应该改为查看Spring HATEOAS。
您需要做的是扩展ResourceSupport
:
class PaginatedRestResponse(val dtos: List<AnyDTO>) : ResourceSupport()
这将为您的班级提供仇恨链接。然后,您可以调用 restTemplate 接受此类型:
response = restTemplate.getForEntity<PaginatedRestResponse>(createUrlWithParams(url, requestPage))
您可以这样检索链接:
response.getLink(Link.REL_NEXT)
response.getLink(Link.REL_PREVIOUS)
推荐阅读
- apache-spark - Apache Spark DStream 与 HDFS 序列文件中的静态数据记录连接的最佳方式是什么?
- mysql - 如何在 MYSQL 中为 varchar 自动递增
- android - Android : 如何修复有关 setting.adzcore.com 的错误
- java - 无法创建参数化类型的数组
- html - 使用 Card-img-overlay 和 card-columns 的问题
- swiftui - 在 SwiftUI 中将变量从一个视图传递到另一个视图时,EnvironmentVariables 不起作用
- python - 从 .txt 文件中获取变量以执行 php 程序
- typescript - 我们可以使函数类型依赖于(派生自?)它的函数类型(当被调用时)?
- django - 从 django 在 s3 中创建用户名目录
- blazor - 如何在 blazor(.razor 页面)中设置默认类型 @typeparam TValue = bool