【问题标题】:How to create JSON for integration tests with spring-data-rest and MockMvc如何使用 spring-data-rest 和 MockMvc 为集成测试创建 JSON
【发布时间】:2017-06-03 04:10:25
【问题描述】:

我在 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 的功能?

【问题讨论】:

标签: java json integration-testing spring-data-rest spring-test


【解决方案1】:

我倾向于构建一个代表 Json 的 Map 并将其序列化为一个字符串,然后我将其用作例如的内容。 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 非常明确。当您做出不兼容的更改时,您会立即意识到。

【讨论】:

    【解决方案2】:

    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")));
    

    【讨论】:

      猜你喜欢
      • 2018-11-19
      • 2015-01-01
      • 2021-04-15
      • 2020-04-04
      • 1970-01-01
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多