【发布时间】:2026-02-07 17:45:01
【问题描述】:
控制器接口
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返回JSON String来验证内容的正确性,但是我想这样做
【问题讨论】:
标签: spring-boot kotlin resttemplate