json - MockServer 和 OkHttp : body type missmatch (json vs string)

标签 json spring-boot integration-testing okhttp mockserver

你好 Stack Overflow 社区!

我正在尝试在一些 Java 集成测试中模拟微服务。

为此,我使用 MockServer 5.5.1 版。 为了完成其余请求,我使用的是 OkHttp 版本 3.13.1

java中的代码:

final SomeDTO requestObject = new SomeDTO(someParams);
final String jsonObject = objectMapper.writeValueAsString(requestObject);
final MediaType MEDIA_TYPE_JSON = MediaType.get("application/json; charset=utf-8");

final RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, jsonObject);
final Request request = new Request.Builder().url("serverUrl").post(requestBody).build();

final Response response = client.newCall(request).execute();
final String responseJson = response.body().string();
final ResultDTO result = objectMapper.readValue(responseJson, ResultDTO.class);

这很好用。但是,当我将 MockServer 附加到匹配器时:

 final MockServerClient client = new MockServerClient("127.0.0.1", 1080);
 client.when(request().withMethod("POST") //
                      .withPath("serverUrl") //
                      .withBody(json(correctJsonString, MatchType.ONLY_MATCHING_FIELDS))) //
       .respond(response().withStatusCode(200) //
                          .withHeaders(new Header("Content-Type", "application/json; charset=utf-8"),
                                        new Header("Cache-Control", "public, max-age=86400"))
                          .withBody(responseJson));

我得到一个request didn't match expectation because: body didn't match, body之间的区别是:

要求:

"body" : {
  "type" : "STRING",
  "string" : "{\"id\":33611,\"prop1\":28,\"prop2\":\"value2\",\"graph\":[...]}",
  "contentType" : "text/plain; charset=utf-8"
}

请求应该匹配:

"body" : {
  "type" : "JSON",
  "json" : "{\"prop2\":\"value2\",\"prop1\":28,\"graph\":[...]}"
}

所以我的问题:

  • 假设由于 "JSON" <-> "STRING" 类型,正文不匹配是否正确?
  • 这是对 MockServer 的错误解释还是 OkHttp 生成了错误的请求? (请求本身确实有效)
  • 有什么解决方法的建议吗?

最佳答案

这是一个 JSON 演示:

    @Test
public void testRemote3() {
    String host = "localhost";
    int port = 1080;
    String url = String.format("http://%s:%d",host,port);
    MockServerClient mockServerClient = new MockServerClient(host,port);
    mockServerClient.when(
            request()
                    .withMethod("POST")
                    .withPath("/order/completed/notify")
                    .withBody(new JsonBody("{\"username\":\"foo1\", \"age\": 13}", Charset.forName("UTF-8"),MatchType.STRICT))
    ).respond(
            response().withStatusCode(200)
                    .withCookie("sessionId", "2By8LOhBmaW5nZXJwcmludCIlMDAzMW")
                    .withHeader("Location", "https://www.mock-server.com")
                    .withBody("{\"username\":\"wang\", \"status\": 1}")
    );
    mockServerClient.when(
            request()
                    .withMethod("POST")
                    .withPath("/order/completed/notify")
                    .withBody(new JsonBody("{\"username\":\"zhao\", \"age\": 3}", Charset.forName("UTF-8"),MatchType.STRICT))
    ).respond(
            response().withStatusCode(200)
                    .withCookie("sessionId", "2By8LOhBmaW5nZXJwcmludCIlMDAzMW")
                    .withHeader("Location", "https://www.mock-server.com")
                    .withBody("{\"username\":\"wang\", \"status\": true}")
    );
    log.info("----------------->calling ");
    Map<String,Object> userInfo = new HashMap<>();
    userInfo.put("age",13);
    userInfo.put("username","foo1");
    String result = OkHttpUtils.postJson(url+"/order/completed/notify",userInfo);
    log.info(result);
    Map<String,Object> fool = new HashMap<>();
    fool.put("age",3);
    fool.put("username","zhao");
    result = OkHttpUtils.postJson(url+"/order/completed/notify",fool);
    log.info(result);
}

关于json - MockServer 和 OkHttp : body type missmatch (json vs string),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54946479/

相关文章:

gradle - 使用 Gradle 运行多个 Spring Boot 微服务

带有 UTF8 字符的 PHP JSON

javascript - 对 wcf 的 Ajax 调用返回未定义

Spring boot 和 Spring Data JPA @Transactional 不工作

java - 使用来自 URI 的参数进行 PostMapping

unit-testing - 如何编写集成测试以与外部 API 交互?

java - h2 数据库从单独的线程访问测试数据

java - @Context 在集成测试期间为 null

javascript - Node JS Express 未定义回调

java - jersey json 尝试解码到同一对象