从Spring RestDocs生成的春季合约:忽略标头



TL;DR:我对这个问题发表了评论,并被要求打开一个新票证,但后来意识到这更像是一个问题,因为Spring RestDocs提供了一种使用操作预处理器实现我想要的东西(忽略合约中不重要的标头)的方法。所以我们在这里,在我们友好的SoF上

问题是我正在尝试从RestDocs测试开始生成合约(如果重要,请使用RestAssuredjunit5)。测试设置(在 Kotlin 中)如下所示:

private val defaultDocument = document("{method_name}", SpringCloudContractRestDocs.dslContract())
lateinit var spec: RequestSpecification
@BeforeEach
internal fun setUp(restDocumentationContextProvider: RestDocumentationContextProvider) {
RestAssured.port = port
spec = RequestSpecBuilder()
.setConfig(
RestAssuredConfig.config()
.objectMapperConfig(
ObjectMapperConfig.objectMapperConfig()
.jackson2ObjectMapperFactory { _, _ -> mapper }
)
)
.addFilter(defaultDocument)
.addFilter(ResponseLoggingFilter())
.log(LogDetail.ALL)
.build()
}

其中mapperport作为Spring豆注射。

服务器生成一个Date标头,这是生成响应的时间。这是由Spring WebMvc自动完成的(我认为),我根本不在乎那个标题。但是,Date标头会导致存根生成失败,因为我决定在多语言世界中使用 Spring Cloud 合同来生成存根并将其上传到 maven 存储库,因为现在服务器生成不同的日期。

正如我在这里指出的,ContractDslSnippet似乎没有提供一种忽略不重要的标头和/或添加匹配器的方法(这仍然是一个悬而未决的问题)。

(简短)问题列表:

  • 如何从生成的合约中过滤掉不重要的标头?
  • 我可以
  • 为标题添加自定义匹配器,就像我可以为正文添加一样吗?

如何使用 Spring RestDocs 预处理器删除不重要的标头:

private val defaultDocument = document("{method_name}", SpringCloudContractRestDocs.dslContract())
lateinit var spec: RequestSpecification
@BeforeEach
internal fun setUp(restDocumentationContextProvider: RestDocumentationContextProvider) {
RestAssured.port = port
spec = RequestSpecBuilder()
.setConfig(
RestAssuredConfig.config()
.objectMapperConfig(
ObjectMapperConfig.objectMapperConfig()
.jackson2ObjectMapperFactory { _, _ -> mapper }
)
)
.addFilter(
documentationConfiguration(restDocumentationContextProvider)
.operationPreprocessors()
.withResponseDefaults(Preprocessors.removeMatchingHeaders("Date"))
)
.addFilter(defaultDocument)
.addFilter(ResponseLoggingFilter())
.log(LogDetail.ALL)
.build()
}

重要的部分是添加新的过滤器(第一个),它负责配置Spring RestDocs以从其所有代码片段(包括合约片段)中删除Date

如何使用默认SpringCloudContractRestDocs.dslContract()添加自定义匹配器:我认为现在实际上是不可能的,但这里可能是错误的(如果有人可以插话并纠正我以防万一,很高兴)

最新更新