Java 如何使用SpringDataREST和MockMvc为集成测试创建JSON

Java 如何使用SpringDataREST和MockMvc为集成测试创建JSON,java,json,integration-testing,spring-data-rest,spring-test,Java,Json,Integration Testing,Spring Data Rest,Spring Test,我在spring数据jpa之上使用spring数据rest 我正在编写集成测试,以使用MockMvc和内存测试数据库测试我的sdrapi 到目前为止,我主要关注get,但现在我正在考虑为POST、PUT和PATCH请求创建测试,看起来我必须编写自己的JSON生成器(可能基于GSON),以便获取相关实体的URL等内容,例如 public class ForecastEntity { @RestResource @ManyToOne(fetch = FetchType.EAGER)

我在spring数据jpa之上使用spring数据rest

我正在编写集成测试,以使用MockMvc和内存测试数据库测试我的sdrapi

到目前为止,我主要关注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"
}
mockMvc.perform(patch(someUri)
  .contentType(APPLICATION_JSON)
  .content(toJson("title", "test-forecast", "unit", "http://localhost/units/test-unit")));

SDR中是否有功能可用于从测试中手动初始化的实体生成JSON?

我倾向于构建一个表示JSON的
映射,并将其序列化为一个字符串,然后将其用作例如
POST
调用的内容

为了方便起见,我喜欢使用番石榴,因为它带有方便的生成器功能

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));
当然,您也可以使用`ObjectMapper'直接序列化实体的实例``

ForecastEntity forecast = new ForecastEntity();
forecast.setTitle("test-forecast");
forecast.setUnit(new UnitEntity("test-unit"));
String json = new ObjectMapper().writeValueAsString(forecast)

我喜欢使用第一个版本,因为通过这种方法,您可以非常明确地发送哪个json。当您做出不兼容的更改时,您会立即意识到。

Mathias,谢谢您的好主意

我想出了一个在测试中使用的简单方法:

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());
}
也许-SDR作者的例子可以帮助: