我正在使用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
在我的SpringBoot 1.4应用程序中创建超媒体链接。它适用于生产,但在通过SpringBoot测试进行测试时我遇到了一些问题。
我有一个简单的测试来检查HATEOAS链接
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MessageControllerTest {
@Autowired
private TestRestTemplate testRestTemplate;
@MockBean
private MessageService messageService;
@Test
public void testHypermedia() throws Exception {
final Message message = createSimpleMessage("1");
given(messageService.getMessagesOfGroupForContact(message.getGroupIdentifier(), message.getCreator().getId())).willReturn(Collections.singletonList(message));
final MessageDto messageDto = testRestTemplate.exchange("/api/messages?groupIdentifier={groupId}&contactId={contactId}", HttpMethod.GET, null, new ParameterizedTypeReference<List<MessageDto>>() {
}, message.getGroupIdentifier(), message.getCreator().getId()).getBody().get(0);
assertThat(messageDto.getLinks().size()).isEqualTo(1);
assertThat(messageDto.getLink("self")).isNotNull();
assertThat(messageDto.getLink("self").getHref()).endsWith("/api/message/1?contactId=creator_1");
}
}
此测试工作正常。网址 / api / messages?groupIdentifier = {groupId}&amp; contactId = {contactId} 返回MessageDaos列表。
但是当切换到测试url / api / message / {messageId}?contactId = {contactId} 时,只返回一个元素getLinks()为空:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MessageControllerTest {
@Autowired
private TestRestTemplate testRestTemplate;
@MockBean
private MessageService messageService;
@Test
public void testHypermedia() throws Exception {
final Message message = createSimpleMessage("1");
given(messageService.getMessagesOfGroupForContact(message.getGroupIdentifier(), message.getCreator().getId())).willReturn(Collections.singletonList(message));
//final ResponseEntity<MessageDto> responseEntity = testRestTemplate.exchange("/api/message/{messageId}?contactId={contactId}", HttpMethod.GET, null, MessageDto.class, message.getId(), message.getCreator().getId());
final MessageDto messageDto = testRestTemplate.getForEntity("/api/message/{messageId}?contactId={contactId}", MessageDto.class, message.getId(), message.getCreator().getId()).getBody();
assertThat(messageDto.getLinks().size()).isEqualTo(1); // breaking
assertThat(messageDto.getLink("self")).isNotNull();
assertThat(messageDto.getLink("self").getHref()).endsWith("/api/message/1?contactId=creator_1");
}
}
使用getForEntity(...)或使用exchange(...)时不起作用。这两种方法都返回一个缺少链接的正确MessageDto。
有什么问题?