2

spring-data-jpaの上にspring-data-restを使用しています。spring-data-restとMockMvcによる統合テストのためのJSONの作成方法

MockMvcとメモリ内テストデータベースを使用して私のSDR APIをテストするための統合テストを書いています。

これまでGETに集中していましたが、今はPOST、PUT、PATCHリクエストのテストを作成しています。自分自身のJSONジェネレータ(おそらくGSONベース)関連エンティティのURLのようなものを取得するために

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

と私は親/子供を持つエンティティを構築します私のテストで:

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

は次のようにJSONを生成する必要があります:

{ 
    "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"))); 
関連する問題