Я пытаюсь использовать TestRestTemplate в Integration-Test Spring Boot Application Integration-Test, чтобы сделать запрос в репозиторий REST Spring Data REST.TestTestplate Spring Boot с HATEOAS PagedResources
Ответ в браузере имеет вид:
{
"links": [
{
"rel": "self",
"href": "http://localhost:8080/apiv1/data/users"
},
{
"rel": "profile",
"href": "http://localhost:8080/apiv1/data/profile/users"
},
{
"rel": "search",
"href": "http://localhost:8080/apiv1/data/users/search"
}
],
"content": [
{
"username": "admin",
"enabled": true,
"firstName": null,
"lastName": null,
"permissions": [ ],
"authorities": [
"ROLE_ADMIN"
],
"accountNonExpired": true,
"accountNonLocked": true,
"credentialsNonExpired": true,
"content": [ ],
"links": [
{
"rel": "self",
"href": "http://localhost:8080/apiv1/data/users/1"
},
{
"rel": "myUser",
"href": "http://localhost:8080/apiv1/data/users/1"
},
{
"rel": "mandant",
"href": "http://localhost:8080/apiv1/data/users/1/mandant"
}
]
},
{
"username": "dba",
"enabled": true,
"firstName": null,
"lastName": null,
"permissions": [ ],
"authorities": [
"ROLE_DBA"
],
"accountNonExpired": true,
"accountNonLocked": true,
"credentialsNonExpired": true,
"content": [ ],
"links": [
{
"rel": "self",
"href": "http://localhost:8080/apiv1/data/users/2"
},
{
"rel": "myUser",
"href": "http://localhost:8080/apiv1/data/users/2"
},
{
"rel": "mandant",
"href": "http://localhost:8080/apiv1/data/users/2/mandant"
}
]
},
{
"username": "user",
"enabled": true,
"firstName": null,
"lastName": null,
"permissions": [ ],
"authorities": [
"ROLE_USER"
],
"accountNonExpired": true,
"accountNonLocked": true,
"credentialsNonExpired": true,
"content": [ ],
"links": [
{
"rel": "self",
"href": "http://localhost:8080/apiv1/data/users/3"
},
{
"rel": "myUser",
"href": "http://localhost:8080/apiv1/data/users/3"
},
{
"rel": "mandant",
"href": "http://localhost:8080/apiv1/data/users/3/mandant"
}
]
}
],
"page": {
"size": 20,
"totalElements": 3,
"totalPages": 1,
"number": 0
}
}
Это испытание:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("unittest")
public class MyUserRepositoryIntegrationTest {
private static Logger logger = LoggerFactory.getLogger(MyUserRepositoryIntegrationTest.class);
private static final int NUM_USERS = 4;
private static final String USER_URL = "/apiv1/data/users";
@Autowired
private TestRestTemplate restTemplate;
@Test
public void listUsers() {
ResponseEntity<PagedResources<MyUser>> response = restTemplate.withBasicAuth("user", "user").exchange(USER_URL,
HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<MyUser>>() {
});
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
logger.debug("Res : " + response.getBody().toString());
assertThat(response.getBody().getContent().size()).isEqualTo(NUM_USERS);
}
@TestConfiguration
public static class MyTestConfig {
@Autowired
@Qualifier("halJacksonHttpMessageConverter")
private TypeConstrainedMappingJackson2HttpMessageConverter halJacksonHttpMessageConverter;
@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder().messageConverters(halJacksonHttpMessageConverter);
}
}
}
Проблема в том, что я не получаю содержание. Интересно, что есть метаданные (пейджинговая информация).
My TestConfig обнаружен, но я думаю, что он не использует «halJacksonHttpMessageConverter» (который я получил отсюда: https://github.com/bijukunjummen/hateoas-sample/blob/master/src/test/java/univ/HALRestTemplateIntegrationTests.java). Вот почему я использовал messageConverters(), а не «дополнительныеMessageConverters()» (безрезультатно).
Вот лог:
m.m.a.RequestResponseBodyMethodProcessor : Written [PagedResource { content: [Resource { content: [email protected], links: [<http://localhost:51708/apiv1/data/users/1>;rel="self", <http://localhost:51708/apiv1/data/users/1>;rel="logisUser"] }, Resource { content: [email protected], links: [<http://localhost:51708/apiv1/data/users/2>;rel="self", <http://localhost:51708/apiv1/data/users/2>;rel="logisUser"] }, Resource { content: [email protected], links: [<http://localhost:51708/apiv1/data/users/3>;rel="self", <http://localhost:51708/apiv1/data/users/3>;rel="logisUser"] }, Resource { content: [email protected], links: [<http://localhost:51708/apiv1/data/users/4>;rel="self", <http://localhost:51708/apiv1/data/users/4>;rel="logisUser"] }], metadata: Metadata { number: 0, total pages: 1, total elements: 4, size: 20 }, links: [<http://localhost:51708/apiv1/data/users>;rel="self", <http://localhost:51708/apiv1/data/profile/users>;rel="profile", <http://localhost:51708/apiv1/data/users/search>;rel="search"] }] as "application/hal+json" using [org.springframework.data.rest.webmvc.config.Rep[email protected]2f58f492]
o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
o.s.web.client.RestTemplate : GET request for "http://localhost:51708/apiv1/data/users" resulted in 200 (null)
o.s.web.servlet.DispatcherServlet : Successfully completed request
o.s.web.client.RestTemplate : Reading [org.springframework.hateoas.PagedResources<at.mycompany.myapp.auth.MyUser>] as "application/hal+json;charset=UTF-8" using [org.springframework.data.rest.webmvc.config.Rep[email protected]10ad95cd]
o.s.b.w.f.OrderedRequestContextFilter : Cleared thread-bound request context: [email protected]
d.l.a.MyUserRepositoryIntegrationTest : Res : PagedResource { content: [], metadata: Metadata { number: 0, total pages: 1, total elements: 4, size: 20 }, links: [] }
Идея переопределяя restTemplate Bean приходит из документации: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-rest-templates-test-utility
Любые идеи, как я могу просто сделать некоторые REST звонки и получить ответ как объект для мои тесты?
Это может быть полезно: http://stackoverflow.com/questions/38468839/spring-data-rest-consume-list-of-entities-java-hateoas-client –
Я просто попробовал это с ClientHttpRequestInterceptor, но он не работает. Кроме того, я могу получить все данные, выполнив getForEntity с помощью String.class. И проверьте журнал (последний поле с цитатой), который читает «Чтение [..PagedResources <...MyUser>] как« application/hal + json; charset = UTF-8 »' –