首页 > 解决方案 > 如何将页面的内容作为列表获取而不是列表在 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来验证内容的正确性,但是我想以这种方式进行

标签: spring-bootkotlinresttemplate

解决方案


我不能说这里的特定问题是什么,但我通常不会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)

推荐阅读