2

spring-data-jpa에서 spring-data-rest를 사용하고 있습니다.spring-data-rest 및 MockMvc를 사용하여 JSON을 생성하는 방법

MockMvc 및 메모리 내 테스트 데이터베이스를 사용하여 SDR API를 테스트하기위한 통합 테스트를 작성하고 있습니다.

지금까지는 GET에 집중했지만 이제는 POST, PUT 및 PATCH 요청에 대한 테스트를 작성하고 있으며 자체 JSON 생성기 (GSON 기반)를 작성해야하는 것처럼 보입니다. 관련 엔티티에 대한 URL과 같은 항목을 얻으려면

ForecastEntity forecast = new ForecastEntity(); 
forecast.setTitle("test-forecast"); 
forecast.setUnit(new UnitEntity("test-unit")); 

이 같은 JSON을 생성해야합니다 :

public class ForecastEntity { 
    @RestResource 
    @ManyToOne(fetch = FetchType.EAGER) 
    @JoinColumn(name = "UNITID", referencedColumnName = "ID") 
    private UnitEntity unit; 
} 

내가 부모/자녀 엔티티를 구축 할 내 테스트에서

{ 
    "title" : "test-forecast", 
    "unit" : "http://localhost/units/test-unit" 
} 

SDR의 기능은 내가 할 수 있는가 테스트에서 수동으로 초기화 된 엔티티에서 JSON을 생성하는 데 사용 하시겠습니까?

+0

어쩌면 [봄 Restbucks] (https://github.com/

나는 시험에 사용하는 간단한 방법을 함께했다 olivergierke/spring-restbucks) - SDR 작성자의 예는 다음을 도울 수 있습니다. [MoneySerializationTest] (https://github.com/olivergierke/spring-restbucks/blob/master/src/test/java/org/springsource/restbucks /payment/web/MoneySerializationTest.java) – Cepr0

답변

2

저는 Json을 나타내는 Map을 작성하는 경향이 있습니다.이 문자열을 문자열로 직렬화합니다. 예를 들어. POST 전화.

편의를 위해 편리한 빌더 기능이 포함되어 있기 때문에 구아바 ImmutableMap을 사용하고 싶습니다. 당신은 또한 직접`ObjectMapper``

이 방법으로는 매우 명시 때문에 나는 첫 번째 버전으로 가고 싶어
ForecastEntity forecast = new ForecastEntity(); 
forecast.setTitle("test-forecast"); 
forecast.setUnit(new UnitEntity("test-unit")); 
String json = new ObjectMapper().writeValueAsString(forecast) 

하는 JSON와 개체의 인스턴스를 직렬화 할 수 물론

String json = new ObjectMapper().writeValueAsString(ImmutableMap.builder() 
    .put("title", "test-forecast") 
    .put("unit", "http://localhost/units/test-unit") 
    .build()); 
mockMvc.perform(patch(someUri) 
    .contentType(APPLICATION_JSON) 
    .content(json)); 

너는 보낸다. 그리고 당신은 호환되지 않는 변화를 만들 때 즉시 깨닫습니다.

1

마티아스, 훌륭한 아이디어에 감사드립니다.

public static String toJson(String ... args) throws JsonProcessingException { 
    Builder<String, String> builder = ImmutableMap.builder(); 
    for(int i = 0; i < args.length; i+=2){ 
    builder.put(args[i], args[i+1]); 
    } 
    return new ObjectMapper().writeValueAsString(builder.build()); 
} 

내가 이런 식으로 그것을 사용 :

mockMvc.perform(patch(someUri) 
    .contentType(APPLICATION_JSON) 
    .content(toJson("title", "test-forecast", "unit", "http://localhost/units/test-unit"))); 
관련 문제