英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论