首页 > 解决方案 > 如何测试 JAX-RS org.glassfish.jersey.message.internal.OutboundJaxrsResponse?

问题描述

我有一个应用程序是几年前的遗产。它结合了 JAX-RS 和 Spring Boot。

我必须进行单元测试@Controller,这是一个 JAX-RS 类,注释为@Component. 我得到了回应OutboundJaxrsResponse。课程本身是密封的,不允许我做太多事情。

是否有可能将它翻译成更可测试的东西,因为我只关心statusand reason

评论:

我不想做Response.ok().build(),因为它忽略了我为什么要测试。当我使用 JUnit5 时,我希望做这样的事情:

assertEquals("My response", entity(response))
assertEquals(200, response.status)

我搜索了不同的解决方案,但 JAX-RS 似乎有不同的测试方法,但我找不到方便且有效的方法。

更新:

我以这种方式定义了端点:

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{key}")
open override fun getStatus(@PathParam("key") key: String): Response {
    return try {
        Response.status(
            Response.Status.OK.statusCode,
            "This okay"
        ).build()
    } catch (e: Exception) {
        Response.status(
            Response.Status.NOT_FOUND.statusCode,
            "Error, resource not found"
        ).build()
    }
}

标签: kotlinjax-rsjunit5

解决方案


我的困惑是因为我没有在对象中看到任何预期的字段,例如 、org.glassfish.jersey.message.internal.OutboundJaxrsResponseentity类似的。contentbody

为了克服这个问题,就我而言,我必须使用response.statusInfo.reasonPhrasewhich 按我的预期工作。

val ID = "abc"
val response: Response = controller.getInfoBy(ID)

assertEquals("ID: abc", response.statusInfo.reasonPhrase)
assertEquals(200, response.status)

注意: statusInfo 包含许多其他有用的字段来检索响应的信息。


推荐阅读