有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Jackson(反)序列化在HTTP响应和测试用例之间不准确

我有一个springboot2.3.2.RELEASEWebFlux应用程序。我有一些JPA实体作为RESTful API响应的一部分返回

我所做的测试(使用@WebFluxTest)根据JSON模式检查HTTP响应和契约。我在这些测试中注入了一个Jackson的ObjecMapper和一个Spring WebTestClient,以根据相应的/预期的JSON模式检查HTTP响应

问题是:如果我在应用程序运行时使用任何HTTP客户机,那么没有元素的集合(在Java端)将作为空数组序列化为JSON——这是我所期望的,无论理论上是否正确;但是在测试用例中,相同的空集合被null值序列化

所以我想知道为什么会有不同?我希望在任何时候都使用相同的JSON字符串

我知道我没有使用不同的ObjectMapper设置——或者我就是这么想的。我没有任何针对该类型的定制Springbean,因此我使用默认情况下SpringBoot注入的任何东西,因此运行应用程序和运行测试时必须相同。Jackson的唯一定制是在application.yml中的应用程序级别完成的:

spring:
  ...
  jackson:
    property-naming-strategy: LOWER_CAMEL_CASE
    serialization:
      write-date-timestamps-as-nanoseconds: false
      write-dates-as-timestamps: true
  ...

I'm using the com.networknt:json-schema-validator:1.0.43 library for the JSON schema implementation.


其中一个测试用例的摘录:

@WebFluxTest(controllers = [ExamController::class])
internal class ExamControllerTest {
  @Autowired
  private lateinit var webClient: WebTestClient

  @Autowired
  private lateinit var mapper: ObjectMapper

  @Test
  @Disabled
  fun getById_ValidateResponseAgainstSchema() {
    // IMPORTANT: If you update anything here, make the corresponding changes also to getById_WhenRecordExists
    webClient.get()
        .uri("/exams/10001030")
        .accept(MediaType.APPLICATION_JSON)
        .exchange()
        .expectStatus().isOk
        .expectBody()
        .consumeWith { result ->
          val schemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V201909)
          this::class.java.getResourceAsStream("/json-schemas/exam/exam-details.json").use {
            Assertions.assertThat(schemaFactory.getSchema(it).validate(mapper.readTree(result.responseBody))).isEmpty()
          }
        }
  }

  // ...
}

使用Testcontainers在Docker容器中创建/播种测试数据


共 (1) 个答案

  1. # 1 楼答案

    禁用DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT,这样Jackson就不会将空数组反序列化为空值