spring - Spring REST Controller 的单元测试 'Location' header

标签 spring rest testng mockmvc

在 Spring REST Controller 中创建资源后,我将在标题中返回它的位置,如下所示。

@RequestMapping(..., method = RequestMethod.POST)
public ResponseEntity<Void> createResource(..., UriComponentsBuilder ucb) {

    ...

    URI locationUri = ucb.path("/the/resources/")
        .path(someId)
        .build()
        .toUri();

    return ResponseEntity.created(locationUri).build();
}

在单元测试中,我正在检查其位置如下。
@Test
public void testCreateResource(...) {
    ...
    MockHttpServletRequestBuilder request = post("...")
        .content(...)
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON);

    request.session(sessionMocked);

    mvc.perform(request)
        .andExpect(status().isCreated())
        .andExpect(header().string("Location", "/the/resources" + id);
}

此结果案例失败并显示以下消息。
java.lang.AssertionError: Response header Location expected:</the/resources/123456> but was:<http://localhost/the/resources/123456>

似乎我必须在预期中为 Location header 提供上下文前缀 http://localhost
  • 硬编码上下文是否安全?如果是这样,为什么?
  • 如果不是,为测试用例正确生成它的正确方法是什么?
  • 最佳答案

    我猜是因为你正在使用 UriComponentsBuilder要构建您的 URI,它会在您的位置 header 中设置主机名。你是否使用过类似 new URI("/the/resources") 的东西,您的测试将通过。

    在你的情况下,我会使用 redirectedUrlPattern匹配重定向 URL:
    .andExpect(redirectedUrlPattern("http://*/the/resources"))
    这将匹配任何主机名,因此您不必对 localhost 进行硬编码。详细了解可以与 AntPathMatcher 一起使用的不同模式here .

    关于spring - Spring REST Controller 的单元测试 'Location' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40931556/

    相关文章:

    java - Mybatis xml resultMap 存在集合和关联问题

    java - 创建 applicationContext.xml 时出错 : Error creating bean with name 'sessionFactory' defined in ServletContext resource

    java - 我可以有多个只为它们所属的组运行的@BeforeMethod 吗?

    java - Minium 使用胶水和浏览器抛出错误

    java - Autowiring 异常

    http - 在 REST API 中处理标志和属性的选项有哪些?

    rest - PayPal REST API 500 内部服务错误仅在实时

    处理资源之间双向关系的 RESTful 方式

    java - 在 NetBeans 8.1 中运行单个 TestNG 测试

    java - TestNG Dataprovider - 过滤测试数据