从Spring HATEOAS 1.0迁移到2.4时,如何正确替换Link.REL_SELF?
Spring HATEOAS 版本迁移后JUnit断言失败修复方案
问题场景
原Spring HATEOAS 1.0版本的JUnit测试代码:
@Test public void processUserExceptionThrown() { when(userService.processAccount(request, account)) .thenThrow(new RuntimeException()); try { userService.processAccount(request); fail("Exception was expected to be thrown, but was not"); } catch (InternalException ex) { assertEquals(Link.REL_SELF, ex.getSelfLink().getRel()); } }
迁移至最新Spring及Spring HATEOAS版本后,修改后的测试代码:
@Test public void processUserExceptionThrown() { when(userService.processAccount(request, account)) .thenThrow(new RuntimeException()); try { userService.processAccount(request); fail("Exception was expected to be thrown, but was not"); } catch (InternalException ex) { assertEquals(Link.of("url", IanaLinkRelations.SELF), ex.getSelfLink().getRel()); } }
执行测试时触发断言失败,错误信息:
org.opentest4j.AssertionFailedError: expected: <<url>;rel="self"> but was: <self>
问题根源
新版本中:
ex.getSelfLink().getRel()返回的是字符串类型的关系名称(如"self")Link.of("url", IanaLinkRelations.SELF)生成的是完整的Link对象,两者类型不匹配,直接对比必然失败- 旧版本
Link.REL_SELF是字符串常量,新版本IanaLinkRelations.SELF是LinkRelation枚举类型,需正确提取其值进行对比
修复方案
保持原测试逻辑不变,修改断言代码为以下两种方式之一:
方式一:直接对比关系名称字符串
assertEquals(IanaLinkRelations.SELF.value(), ex.getSelfLink().getRel());
方式二:通过LinkRelation类型匹配
assertEquals(IanaLinkRelations.SELF, LinkRelation.of(ex.getSelfLink().getRel()));
以上两种方式均可验证异常中self链接的关系正确性,与原测试的最终结果一致。
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

