Kotlin Spring Boot测试与可变数据比较

huangapple go评论59阅读模式
英文:

Kotlin spring boot test with variable data comparison

问题

以下是您要翻译的内容:

我在Kotlin中有一个Spring Boot测试,我想要检查POST请求的响应。响应包含每次生成的UUID,我无法为测试硬编码它。

我如何在测试中避免检查这个UUID,但确保响应的格式是正确的?

例如,我的比较如下所示。我想确认userUUID键存在,但不检查其值。

val response = mvc
    .perform(requestBuilder)
    .andExpect(status().isOk())
    .andExpect(content().string("""{"userUUID":"DONT_CARE","status":"Completed"}"""))
英文:

I have spring boot test in Kotlin where I want to check the response of a POST request. The response contains a UUID that is generated each time, which I cannot hard code for test.

How can I avoid checking this UUID in the test but ensure the format of response is correct?

For example, my comparison looks like the following below. I'd like to confirm the key userUUID is there but not check its value.

    val response = mvc
        .perform(requestBuilder)
        .andExpect(status().isOk())
        .andExpect(content().string("""{"userUUID":"DONT_CARE","status":"Completed"}"""))

答案1

得分: 1

content().string() 不仅接受一个用于检查相等性的字符串,还可以接受一个 hamcrest 匹配器的实例,例如 containsString(str: String) 匹配器,您可以使用它或提供您自己的实现,该实现使用正则表达式来检查结果是否正确。
有关文档,请参阅以下链接:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/result/MockMvcResultMatchers.html
https://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html

英文:

content().string() does not only accept a string to check for equality, it can also accept an instance of a hamcrest matcher, e.g. the containsString(str: String) matcher, which you could use or provide your own implementation, that uses a regex to check if the result is correct.
See here for documentation:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/result/MockMvcResultMatchers.html
https://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html

huangapple
  • 本文由 发表于 2023年6月15日 02:27:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476551.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定