You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin Spring Boot测试:忽略UUID值,验证响应格式

解决方案

方法1:使用JSON Path断言(推荐)

Spring MVC Test内置JSON Path支持,能直接校验字段存在性与格式,无需硬编码动态值。把你原有的字符串匹配替换成以下断言即可:

val response = mvc
    .perform(requestBuilder)
    .andExpect(status().isOk())
    // 确认userUUID字段存在
    .andExpect(jsonPath("$.userUUID").exists())
    // 可选:校验字段值符合UUID格式(按需启用)
    .andExpect(jsonPath("$.userUUID").value(MatchesPattern.matchesPattern("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")))
    // 校验固定的status字段值
    .andExpect(jsonPath("$.status").value("Completed"))

方法2:映射为数据类后校验

定义与响应结构匹配的数据类,将JSON反序列化后仅校验固定字段,UUID只需确认非空:

// 定义响应数据类
data class UserResponse(
    val userUUID: String?,
    val status: String?
)

// 测试代码
val result = mvc
    .perform(requestBuilder)
    .andExpect(status().isOk())
    .andReturn()

// 反序列化响应内容
val objectMapper = ObjectMapper().registerModule(KotlinModule())
val responseBody = objectMapper.readValue(result.response.contentAsString, UserResponse::class.java)

// 执行校验
assertThat(responseBody.status).isEqualTo("Completed")
assertThat(responseBody.userUUID).isNotNull()
// 可选:进一步校验UUID格式
assertThat(responseBody.userUUID).matches("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")

这种方式适配复杂响应结构,灵活性更高。

方法3:正则匹配整个响应字符串

如果响应结构简单,也可以用正则表达式模糊匹配整个JSON字符串,缺点是对字段顺序、空格等格式变化敏感:

val response = mvc
    .perform(requestBuilder)
    .andExpect(status().isOk())
    .andExpect(content().string(
        MatchesPattern.matchesPattern("""{"userUUID":"[0-9a-fA-F-]+","status":"Completed"}""")
    ))

内容的提问来源于stack exchange,提问作者William Ross

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 00:27:11