繁体   English   中英

如何使用spring-data-rest和MockMvc创建用于集成测试的JSON

[英]How to create JSON for integration tests with spring-data-rest and MockMvc

我在spring-data-jpa上使用spring-data-rest。

我正在编写集成测试,以使用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吗?

我倾向于构建一个表示Json的Map ,并将其序列化为一个字符串,然后将其用作eg POST调用的内容。

为了方便起见,我喜欢使用guava ImmutableMap,因为它具有便捷的构建器功能。

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());
}

我这样使用它:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM